How do I build a Java type object at runtime from a generic type definition and runtime type parameters?

前端 未结 6 1166
无人及你
无人及你 2020-12-05 12:16

Assuming a generic type declaration (Java)

class Foo {
    public T bar;
}

how can I, at runtime, instantiate a Type object that r

6条回答
  •  借酒劲吻你
    2020-12-05 12:43

    The usual way around type erasure is:

    class Foo {
    
        Class clazz;
    
        public Foo(Class c) {
            clazz = c;
        }
    
        public T bar {
            return clazz.newInstance();
        }
    }
    

    If there's no no-args constructor for your T, you can do something fancier using reflection on the Class object; once you have an instance of Class, you can get an instance.

    I faced exactly this problem too with gson. I ended up with this:

    public class JsonWrapper {
        private String className;
        private String json; // the output of the gson.toJson() method
    }
    

    And when I needed to deserialise, I did a Class.forName(className) then I had all I needed to call the fromJson() method of the gson library.

    I couldn't believe gson did not support this natively - it seems like such an obvious thing to want to do... get some json and turn that into an object without knowing which class it is beforehand.

提交回复
热议问题