How to allow only classes annotated with some annotation in method parameters in Java?

iJava :

Let's suppose I have annotation @MyAnnotation and two classes:

@MyAnnotation
class Foo {
}

class Bar {
}

and some method that needs class as parameter

someMethod(Class<?> klass)

Is it possible to restrict someMethod parameter only to classes that are annotated with @MyAnnotation? I mean:

someMethod(Foo.class) //Must work
someMethod(Bar.class) //Compiler error

If yes, how to do that?

Slaw :

No, this is not possible. The Class<?> parameter type cannot describe an annotation's presence or lack thereof and thus cannot enforce the presence of an annotation. I think the best you could do here is use a marker interface. For example, if you have the following:

interface Marker {}
class Foo implements Marker {}
class Bar {}

Then you could define your method like so:

void someMethod(Class<? extends Marker> klass) {}

And you'll be able to pass Foo.class as an argument but not Bar.class. A caveat to this approach is that any class which inherits from Foo can also be passed as an argument. This could be different than the behavior you intended since annotations on classes are not inherited unless meta-annotated with @Inherited. Another caveat is that the implementation of the interface becomes part of the class' API (i.e. public contract). The same is not true when placing an annotation unless said annotation is meta-annotated with @Documented.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=403330&siteId=1