I have a situation where I need to programmatically set something that has a parameter of Class<? extends Annotation> but I cannot figure out how to pass in an Annotation class to this method.
For example, if I have javax.persistence.Entity and I try setAnnotation(javax.persistence.Entity.class) I get an error saying Class<Entity> is not applicable for those arguments. However, that is a class that has the @interface attribute; it’s obviously an annotation. What am I doing wrong and how can I appropriately send in a value?
The reason for this is I’m going from Spring XML configuration to class @Configuration. It’s easy enough to do this in an xml file with:
<property name="annotation" value="javax.persistence.Entity" />
but I don’t know what Spring is doing to make that work.
public class Stuff {
private List<Class<? extends Annotation>> annotations;
public List<Class<? extends Annotation>> getAnnotations() {
return annotations;
}
public void setAnnotations(List<Class<? extends Annotation>> annotations) {
this.annotations = annotations;
}
}
public class StuffTest {
@Test
public void test() {
new Stuff().setAnnotations(Collections.singletonList(javax.persistence.Entity.class));
// this does not compile
}
}
Edit:
List list = new ArrayList();
list.add(javax.persistence.Entity.class);
stuff.setAnnotations(list);
works but is there a better way?
This is the API that works for me (both using the Eclipse and javac compilers):
Of course, this would mean you’d have to change some of the inner workings of
Stuffitself…Note also the
Collectionargument type, asCollections.singleton()returns aSet, not aList. Maybe you meant to use aCollections.singletonList()instead?