Get generic type of class at runtime

后端 未结 26 2606
野的像风
野的像风 2020-11-21 04:40

How can I achieve this?

public class GenericClass
{
    public Type getMyType()
    {
        //How do I return the type of T?
    }
}
26条回答
  •  攒了一身酷
    2020-11-21 05:16

    I think there is another elegant solution.

    What you want to do is (safely) "pass" the type of the generic type parameter up from the concerete class to the superclass.

    If you allow yourself to think of the class type as "metadata" on the class, that suggests the Java method for encoding metadata in at runtime: annotations.

    First define a custom annotation along these lines:

    import java.lang.annotation.*;
    
    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface EntityAnnotation {
        Class entityClass();
    }
    

    You can then have to add the annotation to your subclass.

    @EntityAnnotation(entityClass =  PassedGenericType.class)
    public class Subclass {...}
    

    Then you can use this code to get the class type in your base class:

    import org.springframework.core.annotation.AnnotationUtils;
    .
    .
    .
    
    private Class getGenericParameterType() {
        final Class aClass = this.getClass();
        EntityAnnotation ne = 
             AnnotationUtils.findAnnotation(aClass, EntityAnnotation.class);
    
        return ne.entityClass();
    }
    

    Some limitations of this approach are:

    1. You specify the generic type (PassedGenericType) in TWO places rather than one which is non-DRY.
    2. This is only possible if you can modify the concrete subclasses.

提交回复
热议问题