How do I get a class instance of generic type T?

前端 未结 22 1258
猫巷女王i
猫巷女王i 2020-11-21 11:03

I have a generics class, Foo. In a method of Foo, I want to get the class instance of type T, but I just can\'t call T.

22条回答
  •  长情又很酷
    2020-11-21 12:05

    As explained in other answers, to use this ParameterizedType approach, you need to extend the class, but that seems like extra work to make a whole new class that extends it...

    So, making the class abstract it forces you to extend it, thus satisfying the subclassing requirement. (using lombok's @Getter).

    @Getter
    public abstract class ConfigurationDefinition {
    
        private Class type;
        ...
    
        public ConfigurationDefinition(...) {
            this.type = (Class) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
            ...
        }
    }
    

    Now to extend it without defining a new class. (Note the {} on the end... extended, but don't overwrite anything - unless you want to).

    private ConfigurationDefinition myConfigA = new ConfigurationDefinition(...){};
    private ConfigurationDefinition myConfigB = new ConfigurationDefinition(...){};
    ...
    Class stringType = myConfigA.getType();
    Class fileType = myConfigB.getType();
    

提交回复
热议问题