Java - passing class with annotation to generic method

8.2k views Asked by At

I'm working with JPA 2 and have the following method:

private static void wipeTable(EntityManager em, Class<? extends Table> klass) {
    String tableName = klass.getAnnotation(Table.class).name();
    ...
}

I think there's a problem with the Class<? extends Table> parameter. I have an entity class like so:

@Entity
@Table(name = "collections")
public class Collection extends MyOtherClass implements Serializable { ... }

I can do Collection.class.getAnnotation(Table.class).name() just fine, so I want to be able to pass Collection as a parameter. Just calling wipeTable(em, Collection.class); has the following error, though:

The method wipeTable(EntityManager, Class<? extends Table>) in the type FetchData is not applicable for the arguments (EntityManager, Class<Collection>)

I tried just having the parameter be Class klass, with no generics:

private static void wipeTable(EntityManager em, Class klass) {
    String tableName = ((Table)klass.getAnnotation(Table.class)).name();

This caused my IDE to suggest:

Class is a raw type. References to generic type Class should be parameterized

I'm using Java 1.5. Is there a way to say "give me a parameter of type Class that is annotated with @Table"?

1

There are 1 answers

3
Perception On BEST ANSWER

I understand what you are trying to accomplish, but realize that Collection does not extend Table, it has a Table annotation on it. Change your signature to something like this:

private static <T> void wipeTable(EntityManager em, Class<T> klass)

As to your second point, there is no way when passing your Class parameter to place a restriction on it to have a particular annotation. But you can check for the presence of annotation in your method:

Table tableAnnotation = klass.getAnnotation(Table.class);
if(tableAnnotation != null) {
    // logic here
}