【发布时间】:2016-05-20 03:43:09
【问题描述】:
我通过以下方式获得 Java 类的列表:
List<String> cF = classFinder.findClassesInPackage("com.some.test", Info.class);
其中classFinder 是服务/类,findClassesInPackage 方法查找包com.some.test 中包含@Info 注释的所有类。 Info.class是第二个参数,只是接口而已。
我的列表cF 现在包含以下内容:
[com.some.test.example.FollTest, com.some.test.example.SubsTest, ..]
现在,我将这个 List cF 转换为 Set 以通过以下方式删除重复的方法:
Set<String> set = new HashSet<String>(cF);
目标:
我想在这个集合上iterate,这样我就可以得到所有的classes one-by-one,最后得到每个类中的所有Info 注释并打印它们。我需要这个,因为我会在之后解析这些注释。
我的担忧:集合元素现在是字符串,我如何将它们转换为实际的类? (For example: out of my first element in set: com.some.test.example.FollTest, I just want FollTest that too in class form)
这是我首先要为单个元素做的事情:
Object check = set.toArray()[0]; - 仍然是一个对象/字符串,而不是我想要的实际类。
然后用于阅读注释(例如):
for (Annotation annotation : ClassName.class.getAnnotations()) {
Class<? extends Annotation> type = annotation.annotationType();
System.out.println("Values of " + type.getName());
for (Method method : type.getDeclaredMethods()) {
Object value = method.invoke(annotation, (Object[])null);
System.out.println(" " + method.getName() + ": " + value);
}
}
How do I get above ClassName? (although I have them in the String/Object form as part of list/set).
更新的问题:另外,一旦我找到类名,如何获取该类中的所有注释并将它们打印出来?
请参阅:http://www.java2s.com/Code/Java/Reflection/Getannotationbyannotationclass.htm 了解如何获取特定类中的注释。
【问题讨论】:
-
我更新了问题。
标签: java class testing casting annotations