代码之家  ›  专栏  ›  技术社区  ›  ChiMo

基类中子类的Java泛型初始化

  •  0
  • ChiMo  · 技术社区  · 6 年前


    从本质上说,我有一堆扩展抽象类的类 BaseClass 需要初始化并添加到 instance 如果没有密钥,则映射。
    子类被多次重用,但基于 key 参数。

    我希望避免反射,如果模板不是“Java方式”,也不介意更改模板。

    public abstract class BaseClass<T> {
        protected Map<String, T> instance = new HashMap<String, T>();
    
        public T Get(String key) {
            if (this.instance.containsKey(key)) {
                return this.instance.get(key);
            } 
            T item = new T(key); // Obviously this line errors but you get the idea
            instance.put(key, item);
            return item;
        }
    }
    
    // Example top class which extends my base class
    public class TopClass extends BaseClass<TopClass> {
        public TopClass(String key) {
            // Do unique initialization stuff
        }
    }
    
    3 回复  |  直到 6 年前
        1
  •  1
  •   S.K.    6 年前

    因为泛型类型在运行时被删除,所以不能这样做。您可以改为使用类变量,如下所示:

    public T Get(Class<T> clazz, String key) throws Exception {
        if (this.instance.containsKey(key)) {
            return this.instance.get(key);
        } 
        T item = clazz.getDeclaredConstructor(String.class).newInstance(key);
        instance.put(key, item);
        return item;
    }
    
        2
  •  1
  •   janardhan sharma    6 年前

    我有另一种方法。

       public interface MyIinterface{
          public void doSomething();
       }
    

    创建此接口的许多实现。

    @Component
    public class MyImplementation1 implements MyInterface{
    
        @Override
        public void doSomething(){
    
        }
    }
    

    用@Component注释所有实现。

    @Component
    public class MyImplementation1 implements MyInterface{
    .
    .
    

    在某个Util类中有一个方法,它将基于字符串键获得实现。

    public static MyInterface getImplementation(String name){
    
      ApplicationContext context;
      return context.getBeanByName(name);
    
    }