我正在使用 JPA 2 并有以下方法:
private static void wipeTable(EntityManager em, Class<? extends Table> klass) {
String tableName = klass.getAnnotation(Table.class).name();
...
}
我认为 Class<? extends Table>
有问题范围。我有一个像这样的实体类:
@Entity
@Table(name = "collections")
public class Collection extends MyOtherClass implements Serializable { ... }
我可以Collection.class.getAnnotation(Table.class).name()
很好,所以我希望能够通过Collection
作为参数。只需调用wipeTable(em, Collection.class);
但有以下错误:
The method wipeTable(EntityManager, Class<? extends Table>) in the type FetchData is not applicable for the arguments (EntityManager, Class<Collection>)
我尝试将参数设置为 Class klass
,没有泛型:
private static void wipeTable(EntityManager em, Class klass) {
String tableName = ((Table)klass.getAnnotation(Table.class)).name();
这导致我的 IDE 提出建议:
Class is a raw type. References to generic type Class should be parameterized
我使用的是 Java 1.5。有没有办法说“给我一个 Class
类型的参数,并用 @Table
注释”?
最佳答案
我明白你想要完成什么,但意识到 Collection 不扩展 Table,它上面有一个 Table 注释。将您的签名更改为如下所示:
private static <T> void wipeTable(EntityManager em, Class<T> klass)
关于第二点,在传递 Class 参数时无法对其进行限制以具有特定的注释。但是您可以检查方法中是否存在注释:
Table tableAnnotation = klass.getAnnotation(Table.class);
if(tableAnnotation != null) {
// logic here
}
关于Java - 将带有注释的类传递给泛型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8826329/