Java 在运行时使用参数实例化类

标签 java dynamic-typing abstract-factory

我正在使用一个抽象工厂来返回具体子类的实例。我想在给定具体类名的字符串的情况下在运行时实例化子类。我还需要将参数传递给构造函数。类结构如下:

abstract class Parent {

  private static HashMap<String, Child> instances = new HashMap<String,Child>()

  private Object constructorParameter;  

  public static Child factory(String childName, Object constructorParam){

     if(instances.keyExists(childName)){
       return instances.get(childName);
     }

     //Some code here to instantiate the Child using constructorParam, 
     //then save Child into the HashMap, and then return the Child.
     //Currently, I am doing:
     Child instance = (Child) Class.forName(childClass).getConstructor().newInstance(new Object[] {constructorParam});
     instances.put(childName, instance);
     return instance;
  }

  //Constructor is protected so unrelated classes can't instantiate
  protected Parent(Object param){ 
    constructorParameter = param;
  }

}//end Parent

class Child extends Parent {
    protected Child(Object constructorParameter){
      super(constructorParameter);
    }
}

我上面的尝试抛出以下异常:java.lang.NoSuchMethodException: Child.<init>() ,然后是堆栈跟踪。

感谢任何帮助。谢谢!

最佳答案

Constructor<?> c = Class.forName(childClass).getDeclaredConstructor(constructorParam.getClass());
c.setAccessible(true);
c.newInstance(new Object[] {constructorParam});

getConstructor 方法采用Class 参数来区分构造函数。但它仅返回公共(public)构造函数,因此您需要 getDeclaredConstructor(..)。然后你需要 setAccessible(true)

关于Java 在运行时使用参数实例化类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8249050/

相关文章:

java - 如何在 Java Stream 的单个步骤上使用并行执行

c++ - 嵌入式 C++ : dynamic typing without dynamic allocation?

c++ - 静态变量与类型推断

variables - 动态类型语言中 map /列表的变量命名约定

Java 泛型和设计模式 : not parameterizing a reference to a generic type is always a bad thing?

c# - 设计模式 : Abstract Factory and Generic Repository

c# - 使用通过 DI 容器注入(inject)的抽象工厂

java - 列表的 Kotlin Gson 自定义反序列化器

java - 如何使用命令提示符使用 tomcat 调试 Web 项目

java - 使 Sprite 从边缘反弹