Question

I'm having a tough time trying to figure out how to get a reference to a java.lang.annotation.Annotation from its actual implementing class.

The annotation itself looks like this (from a framework):

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface RequiresPermissions {
    ...snip...
}

In my using code, I would like to do something like this:

Annotation requiresPermissionAnnotation = RequiresPermissions.class;

I cannot, for the life of me, figure out what or how to cast this, or what typing I can employ to get it.

As a work around, I could have a simple class that has a method with this annotation (and others), and use reflection methods on the Class to get the java.lang.annotation.Annotation, but that just seems odd..

Thanks!

Était-ce utile?

La solution

An instance of the annotation only exists for an annotated type/method. This is how you can get it

Annotation requiresPermissionAnnotation = SomeAnnotatedClass.class.getAnnotation(RequiresPermissions.class);

You can cast to RequiresPermissions to access any attributes.

RequiresPermissions requiresPermissions = (RequiresPermissions) requiresPermissionAnnotation;

or get it directly

RequiresPermissions requiresPermissions = SomeAnnotatedClass.class.getAnnotation(RequiresPermissions.class);

For a method

Annotation requiresPermissionAnnotation = someMethodInstance.getAnnotation(RequiresPermissions.class);

Autres conseils

Say, that you have some class MyClass, which is annotated with the RequiresPermissions annotation:

@RequiresPermissions("something")
public class MyClass {
    // ...
}

If you want to see the values of the annotation for MyClass in your program, you can do this:

RequiresPermissions anno = MyClass.class.getAnnotation(RequiresPermissions.class);

System.out.println(anno.value());

(I don't know what attributes your RequiresPermissions annotation has; you can call them on the anno object to get the values).

The property .class returns a Class object, which you'll have to assign to any super type of Class. It's not an instance of the annotation, so trying to assign it to an Annotation won't work. To keep a reference to the type of an annotation, you have a few options:

// use the actual class
Class<MyAnnotation> annotationClass1 = MyAnnotation.class;

// use a bounded wildcard
Class<? extends Annotation> annotationClass2 = (Class<? extends Annotation>) MyAnnotation.class;

// use an unbound wildcard, not recommended
Class<?> annotationClass3 = MyAnnotation.class;
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top