简体   繁体   English

查找对象参数化注释的运行时classtype

[英]Find runtime classtype of an object's parametrized annotation

I'd like to retrieve the actual class of the generic type that is found on an object's parametrized marker interface. 我想检索在对象的参数化标记接口上找到的泛型类型的实际类。 Is this even possible? 这甚至可能吗?

The marker interface: 标记界面:

public interface MarkerInterface<T> {}

The method i'd like to have: 我想要的方法:

public class findClassForParametrizedMarkerInterface(MarkerInterface<T> markedObjectThatCouldExtendSomeRandomClass){

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

}

For those wishing to know why I would like to do this: I have multiple dto jpa entities for some heavy jpa entities. 对于那些希望知道我为什么要这样做的人:我有一些dto jpa实体用于一些重jpa实体。 I'd like to create a generic service that retrieves the correct full entity spring data jpa repository for the supplied dto. 我想创建一个通用服务,为所提供的dto检索正确的完整实体spring数据jpa存储库。 The dto's have a marker interface that specifies as parametrized generic type the full entity class. dto有一个标记接口,它将完整的实体类指定为参数化泛型类型。

Edit: a good discussion can be found at Get generic type of class at runtime . 编辑: 在运行时可以在Get泛型类中找到一个很好的讨论。 The simplest solution is to pass a reference to the class at the time of instantiation of the object. 最简单的解决方案是在实例化对象时传递对类的引用。 Maintain a reference to this class to return when needed. 保持对此类的引用以在需要时返回。 This is due to Java not holding onto generics at runtime. 这是因为Java在运行时没有保留泛型。 The generic info is available in metadata if you want to use the verbose reflection api to retrieve it. 如果要使用详细反射API来检索通用信息,则可以使用元数据。

use getClass() on the object itself. 在对象本身上使用 getClass()

public final Class getClass() Returns the runtime class of this Object. public final类getClass()返回此Object的运行时类。 The returned Class object is the object that is locked by static synchronized methods of the represented class. 返回的Class对象是由所表示的类的静态同步方法锁定的对象。 The actual result type is Class where |X| 实际结果类型是Class,其中| X | is the erasure of the static type of the expression on which getClass is called. 是调用getClass的表达式的静态类型的擦除。 For example, no cast is required in this code fragment: 例如,此代码片段中不需要强制转换:

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

Returns: The Class object that represents the runtime class of this object. 返回:表示此对象的运行时类的Class对象。 See Also: Literals, section 15.8.2 of The Java™ Language Specification. 另请参阅:文字,Java™语言规范的第15.8.2节。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM