How can I instantiate a generic type in Java?

后端 未结 6 867
遥遥无期
遥遥无期 2020-12-17 16:26

I\'ve added a human-readable configuration file to my app using java.util.Properties and am trying to add a wrapper around it to make type conversions easier. Specifically,

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-17 16:53

    Generics are implemented using type erasure in Java. In English terms, most generic information are lost at compile time, and you can't know the actual value of T at runtime. This means you simply can't instanciate generic types.

    An alternate solution is to provide your class with the type at runtime:

    class Test {
    
        Class klass;
    
        Test(Class klass) {
            this.klass = klass;
        }
    
        public void test() {
            klass.newInstance(); // With proper error handling
        }
    
    }
    

    Edit: New example closer to your case

    static  T getProperty(String key, T fallback, Class klass) {
        // ...
    
        if (value == null) {
            return fallback;
        }
        return (T) klass.newInstance(); // With proper error handling
    }
    

提交回复
热议问题