【问题标题】:Convert Java Object/String to actual Class [duplicate]将Java对象/字符串转换为实际的类[重复]
【发布时间】: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


【解决方案1】:

你应该可以用Class.forName()做到这一点

示例

String className = "com.some.test.example.FollTest";

Class c = Class.forName(className);

Annotation[] annotation = c.getAnnotations();

【讨论】:

  • 我得到这个:[Ljava.lang.annotation.Annotation;@4475a0c6 作为上述代码的输出。
  • 我必须修剪初始部分吗?直到我到达 FollTest?那么getAnnotations() 将如何工作?
  • 我想,通过 for 循环访问会有所帮助:for (int i = 0; i &lt; annotation.length; i++) { System.out.println(annotation[i]); }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-13
  • 2020-01-25
  • 2020-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-02
相关资源
最近更新 更多