Inferring java generics parameters at runtime using reflection

前端 未结 2 1146
栀梦
栀梦 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 {
        private final Class clazz;
        public MyClass(Class clazz) {
            this.clazz=clazz;
        }
    }
    

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

    MyClass object = new MyClass(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.

提交回复
热议问题