Java 1.5.0.12 and custom Annotations at Runtime

萝らか妹 提交于 2019-12-23 17:02:59

问题


I'm in a project where I need to use the above specific JAVA Version. And I wan't to use a custom annotation and query it's presence during RUNTIME using reflection. So I wrote an annotation, a class to annotate and a test class. The problem ist that, the annotation is not there. When I use one of the built in Annotations, everything is fine, the annotation is there. When I try my code under JAVA 1.6 everything is fine...

Is there a known bug in this java version or do I need to add something more?

BR Markus

The code:

// The annotation
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Retention(RUNTIME) 
public @interface GreetsTheWorld {
  public String value();
}

// The Annotated Class
@GreetsTheWorld("Hello, class!") 
public class HelloWorld {

  @GreetsTheWorld("Hello, field!") 
  public String greetingState;

  @GreetsTheWorld("Hello, constructor!") 
  public HelloWorld() {
  }

  @GreetsTheWorld("Hello, method!") 
  public void sayHi() {
  }
}

// The test
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class HelloWorldAnnotationTest {

  public static void main( String[] args ) throws Exception {
    //access the class annotation
    Class<HelloWorld> clazz = HelloWorld.class;
    System.out.println( clazz.getAnnotation( GreetsTheWorld.class ) );

    //access the constructor annotation
    Constructor<HelloWorld> constructor = clazz.getConstructor((Class[]) null);
    System.out.println(constructor.getAnnotation(GreetsTheWorld.class));

    //access the method annotation
    Method method = clazz.getMethod( "sayHi" );
    System.out.println(method.getAnnotation(GreetsTheWorld.class));

    //access the field annotation
    Field field = clazz.getField("greetingState");
    System.out.println(field.getAnnotation(GreetsTheWorld.class));
  }
}

回答1:


I finally found what was the problem: Everything is fine and works. The one problem I had was, that I used the default java settings from my company, and they set Compiler Compliance and Source File compatibility to 1.5. But the class file compatibility was set to 1.2, and there were no annotations in this version. After enabling the project specific settings and changing the class file compatibility to 1.5, everything works fine.

Thanks for your help Markus



来源:https://stackoverflow.com/questions/4714484/java-1-5-0-12-and-custom-annotations-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!