3

我想检索在对象的参数化标记接口上找到的泛型类型的实际类。这甚至可能吗?

标记界面:

public interface MarkerInterface<T> {}

我想要的方法:

public class findClassForParametrizedMarkerInterface(MarkerInterface<T> markedObjectThatCouldExtendSomeRandomClass){

    //How to retrieve the class T, or it's name?

}

对于那些想知道我为什么要这样做的人:对于一些重型 jpa 实体,我有多个 dto jpa 实体。我想创建一个通用服务,为提供的 dto 检索正确的完整实体 spring 数据 jpa 存储库。dto 有一个标记接口,它将完整实体类指定为参数化的泛型类型。

4

1 回答 1

0

编辑:可以在Get generic type of class at runtime找到一个很好的讨论。最简单的解决方案是在对象实例化时传递对类的引用。维护对此类的引用以在需要时返回。这是因为 Java 在运行时没有保留泛型。如果您想使用详细反射 API 来检索通用信息,则元数据中提供了通用信息。

getClass()在对象本身上使用。

public final Class getClass() 返回此对象的运行时类。返回的 Class 对象是被表示类的静态同步方法锁定的对象。实际结果类型是 Class where |X| 是调用 getClass 的表达式的静态类型的擦除。例如,此代码片段中不需要强制转换:

数 n = 0; 类 c = n.getClass();

返回: 表示此对象的运行时类的 Class 对象。另请参阅:Literals,Java™ 语言规范的第 15.8.2 节。

http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#getClass()

于 2014-07-18T11:56:25.873 回答