Get type of a generic parameter in Java with reflection

后端 未结 18 1914
死守一世寂寞
死守一世寂寞 2020-11-22 05:56

Is it possible to get the type of a generic parameter?

An example:

public final class Voodoo {
    public static void chill(List aListWithTy         


        
18条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 06:14

    You can get the type of a generic parameter with reflection like in this example that I found here:

    import java.lang.reflect.ParameterizedType;
    import java.lang.reflect.Type;
    
    public class Home {
        @SuppressWarnings ("unchecked")
        public Class getTypeParameterClass(){
            Type type = getClass().getGenericSuperclass();
            ParameterizedType paramType = (ParameterizedType) type;
            return (Class) paramType.getActualTypeArguments()[0];
        }
    
        private static class StringHome extends Home{}
        private static class StringBuilderHome extends Home{}
        private static class StringBufferHome extends Home{}   
    
        /**
         * This prints "String", "StringBuilder" and "StringBuffer"
         */
        public static void main(String[] args) throws InstantiationException, IllegalAccessException {
            Object object0 = new StringHome().getTypeParameterClass().newInstance();
            Object object1 = new StringBuilderHome().getTypeParameterClass().newInstance();
            Object object2 = new StringBufferHome().getTypeParameterClass().newInstance();
            System.out.println(object0.getClass().getSimpleName());
            System.out.println(object1.getClass().getSimpleName());
            System.out.println(object2.getClass().getSimpleName());
        }
    }
    

提交回复
热议问题