Inferring java generics parameters at runtime using reflection

前端 未结 2 1122
栀梦
栀梦 2021-01-13 16:04

I have a method with the following signature:

// Converts a json string to a list of objects
// Assumption: json is an array, and all items in the list are o         


        
相关标签:
2条回答
  • 2021-01-13 16:31

    The only way I know of to guarantee to have access to the type at run time is to make it a parameter to the object constructor thus:

    class MyClass<T> {
        private final Class<T> clazz;
        public MyClass(Class<T> clazz) {
            this.clazz=clazz;
        }
    }
    

    You then have to pass the class when you instantiate the object:

    MyClass<String> object = new MyClass<String>(String.class);
    

    Obviously, in your case, you have what is effectively a static utility method and no object, so I think you're stuck with either the Class parameter or else some kind of template object.

    0 讨论(0)
  • 2021-01-13 16:36

    Due to type erasure, you definitely can't "infer" what T is--it doesn't even exist at runtime. The closest you could come is inspect the values in defValue (if it has values) and get the class of the elements there.

    Class<?> tType = defValue.get(0).getClass();
    
    if (Boolean.class.isAssignableFrom(tType)) { //...  
    

    Edit

    With regards to your thinking of using reflection like getTypeArguments(), etc. Those only provide data for declared types, never actual types. So for example, if you got a handle to the Method object and called getTypeParameters(), you'd just get an array containing a type object representing T--not the actual type that T represents at some specific runtime invocation.

    0 讨论(0)
提交回复
热议问题