编程语言
首页 > 编程语言> > 为什么我无法从已加载的Java类中检测注释?

为什么我无法从已加载的Java类中检测注释?

作者:互联网

我有一个插件,我想从我的maven项目中访问模型包的类列表.到目前为止,我只是这样做将类加载到插件中:

try {
            runtimeClasspathElements = project.getRuntimeClasspathElements();

        } catch (DependencyResolutionRequiredException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        URL[] runtimeUrls = new URL[runtimeClasspathElements.size()];
        for (int i = 0; i < runtimeClasspathElements.size(); i++) {
          String element = (String) runtimeClasspathElements.get(i);
          try {
            runtimeUrls[i] = new File(element).toURI().toURL();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

newLoader = new URLClassLoader(runtimeUrls,
      Thread.currentThread().getContextClassLoader());
      try {          class=newLoader.loadClass("com.pkl.bc.personnaldata.model.Personne");

    if(class!=null)
        System.out.println(class.getCanonicalName());
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

直到这里,我才能看到我班的全名.

System.out.println(class.getDeclaredFields());
System.out.println(class.isAnnotationPresent(EditColumn.class));
for (Field f : class.getDeclaredFields()) {

                EditColumn v = f.getAnnotation(EditColumn.class);
                if (v != null) {

                    System.out.println(v.tableName());
                    System.out.println(v.oldName());

                }

            }

但我什么也没得到,这是输出:

[Ljava.lang.reflect.Field;@398f573b
false

我也尝试使用反射

Reflections reflections = new Reflections("com.pkl.bc.personnaldata.model.Personne");

          Set<Field> annotated = reflections.getFieldsAnnotatedWith(EditColumn.class);

          System.out.println(annotated);

这给了我一个空白清单.
这是我的注释:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface EditColumn {

    String oldName() default "";

    String newName() default "";

    String tableName() default "";
}

带注释的字段:

@EditColumn(newName = "main_adress", oldName = "adress", tableName = "Personne")
    private String main_adress;

解决方法:

您已经在使用其批注来检索该类,但是您只需要添加一个循环即可为您拥有的每个字段初始化所有批注.

尝试这个示例,当已加载的类的字段可用时,它将打印注释名称及其值.

  for (Field f : loadedClass.getDeclaredFields()) {
                System.out.println(f.getName());
                for (Annotation a : f.getAnnotations()) {
                    System.out.println("## SHOWING ANNOTATION FOR FIELD:" + f.getName());
                    System.out.println(a.toString());
                }


            }

您可以解析toString以获取该注释上的值.
等待您的反馈.

标签:reflection,maven,maven-plugin,annotations,java
来源: https://codeday.me/bug/20191026/1934122.html