Markus Alexander
Markus Alexander

Reputation: 51

Java 1.5.0.12 and custom Annotations at Runtime

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));
  }
}

Upvotes: 3

Views: 1954

Answers (1)

Markus Alexander
Markus Alexander

Reputation: 51

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

Upvotes: 1

Related Questions