[英]Java - passing class with annotation to generic method
I'm working with JPA 2 and have the following method: 我正在使用JPA 2,并且具有以下方法:
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>
我认为
Class<? extends Table>
有问题Class<? extends Table>
Class<? extends Table>
parameter. Class<? extends Table>
参数。 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. 我可以做
Collection.class.getAnnotation(Table.class).name()
很好,所以我希望能够将Collection
作为参数传递。 Just calling wipeTable(em, Collection.class);
只是调用
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>)
FetchData类型的方法擦拭表(EntityManager,Class <?extended Table>)不适用于参数(EntityManager,Class <Collection>)
I tried just having the parameter be Class klass
, with no generics: 我尝试仅使参数为
Class klass
,而没有泛型:
private static void wipeTable(EntityManager em, Class klass) {
String tableName = ((Table)klass.getAnnotation(Table.class)).name();
This caused my IDE to suggest: 这导致我的IDE建议:
Class is a raw type.
类是原始类型。 References to generic type Class should be parameterized
泛型类型Class的引用应参数化
I'm using Java 1.5. 我正在使用Java 1.5。 Is there a way to say "give me a parameter of type
Class
that is annotated with @Table
"? 有没有办法说“给我一个用
@Table
注释的Class
类型的参数”?
I understand what you are trying to accomplish, but realize that Collection does not extend Table, it has a Table annotation on it. 我了解您要完成的工作,但是意识到Collection不会扩展Table,它上面带有Table批注。 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. 关于第二点,在传递Class参数时没有办法对其施加限制以使其具有特定注释。 But you can check for the presence of annotation in your method:
但是您可以检查方法中是否存在注释:
Table tableAnnotation = klass.getAnnotation(Table.class);
if(tableAnnotation != null) {
// logic here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.