将 Class.getEnumConstants 转换为 String

huangapple go评论62阅读模式
英文:

Convert Class.getEnumConstants to String

问题

这个测试案例是为了验证通用枚举生成器。它会生成在一个 XML 文件中列出的枚举。

测试案例是循环遍历每个生成的枚举类,并验证枚举常量是否与从 XML 生成的对象相匹配。

1. 从枚举获取枚举常量列表:
Class<?> c = classLoader.loadClass("enum.java");
System.out.println(Arrays.asList(c.getEnumConstants()));
[x,y,z]

2. 从从 XML 生成的对象中列出枚举值:
List<String> str1 = ["x","y","z"];

现在我想要比较 1 和 2。怎么做?

我参考了 https://docs.oracle.com/javase/tutorial/reflect/special/enumMembers.html

英文:

This test case is to validate the generic enum generator. This generates the enums listed in an xml file.

Test case is to looping through each Enum class generated and verify if the enum constants matches the object generated from XML.

1. List of Enum constants from Enum:
Class&lt;?&gt; c = classLoader.loadClass(&quot;enum.java&quot;);
System.out.println(Arrays.asList(.getEnumConstants()));
[x,y,z]

2. List the Enum values from the Object generated from XML:
List&lt;String&gt; str1 = [&quot;x&quot;,&quot;y&quot;,&quot;z&quot;];

Now I wanted to compare 1 and 2. How to do?

I referenced https://docs.oracle.com/javase/tutorial/reflect/special/enumMembers.html

答案1

得分: 1

java.lang.Class.getEnumConstants() 方法返回此枚举类的元素如果该 Class 对象不表示枚举类型则返回 null方法 .name() 将枚举常量的名称作为字符串返回您可以使用它与字符串列表进行比较

首先将结果转换为类型为 String 的 ArrayList

    ArrayList<String> list1AsString = new ArrayList<>();
    for(EnumName enumInstance : list1){
     list1AsString.add(enumInstance.name()); 
    }
然后您可以进行比较

    list1AsString.equals(list2);

[枚举的方法][1]

  [1]: https://docs.oracle.com/javase/7/docs/api/java/lang/Enum.html
英文:

java.lang.Class.getEnumConstants() returns the elements of this enum class or null if this Class object does not represent an enum type. The methode .name() returns the name of a enum constant as a String. You can use it to compare to the Sting List.

First you convert the result into an ArrayList of type String

ArrayList&lt;String&gt; list1AsString = new ArrayList&lt;&gt;();
for(EnumName enum:list1){
 list1AsString.add(enum.name()); 
}

Then you can compare them.

list1AsString .equals(list2);

Methode of Enum

huangapple
  • 本文由 发表于 2020年4月8日 16:48:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/61096734.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定