有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我对java非常陌生,不太清楚如何从“基类”初始化泛型类型/子类
本质上,我有一组类,它们扩展了抽象类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
    }
}

共 (2) 个答案

  1. # 1 楼答案

    我有另一种方法

    有一个接口MyInterface

       public interface MyIinterface{
          public void doSomething();
       }
    

    创建此接口的许多实现

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

    在依赖项中使用spring core JAR

    用@Component注释所有实现

    @Component
    public class MyImplementation1 implements MyInterface{
    .
    .
    

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

    public static MyInterface getImplementation(String name){
    
      ApplicationContext context;
      return context.getBeanByName(name);
    
    }
    
  2. # 2 楼答案

    由于泛型类型在运行时被擦除,因此无法执行此操作。您可以改为使用类变量,如下所示:

    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;
    }