1

我有一个类,我在静态块中初始化了 hashmap。通过密钥,我检索了一个类的值。为了为这个类创建对象。我已经使用构造函数类来获取构造函数并传递参数和创建的对象。

我在哈希图中有两个班级。要为 EchoExpression 创建对象,我需要传递两个参数,而对于 OutExpression 类,我只需要传递一个参数(字符串)。

  1. 根据键返回的类,我需要执行要获取和实现的构造函数,无论是带有一个参数还是两个参数的构造函数。

  2. 在 EchoExpression 中,构造函数包含两个参数。

例如:

JXPathExpression check = new JXPathExpression(String expression, Class<?> type)

String 属于 String.class 但 Class 类型参数也属于什么类?这样我就可以使用它来获取构造函数

public class ExampleFactory {

    private static HashMap<String,Class<?>> hmap = new HashMap<String,Class<?>>();

    static
    {                   
        hmap.put("echo", EchoExpression.class);         
        hmap.put("Out", OutExpression.class);                       
    }

    public void getExpo(String key,String expression)
      {
        Class aClass =map.get(key);

//Constructor implementation for OutExpression where only one argument string is passed

        Constructor constructor = aClass.getConstructor(new Class[]{String.class});

        Object object= constructor.newInstance(expression);

//Need constructor for passing two arguments string and class<?> for EchoExpression

        return null;        
      }                
}
4

2 回答 2

2

对于这样的事情,您应该在所有情况下尝试使用统一的构造函数参数或存储每个类的参数的方法。

现在回答你的问题。Class<?>是对未知类的引用。基本上到任何班级。使用它时,它或多或少等于Class<Object>因为所有类都Object作为父类。

要使用具有多个参数的构造函数,您首先需要获取合适的构造函数。在这一点上,如果类不支持具有这种参数配置的实例,它已经可以获取发生的错误。获取构造函数的工作方式如下:

aClass.getConstructor(new Class[]{String.class, Object.class, ...});

This works with as many argument types as you like. Creating the new instance of the class then works this way:

constructor.newInstance(theString, theObject, ...);

The function newInstanace is implemented as many arguments as needed. So depending on how many arguments the constructor that was requested requires the newInstance function will be able to work with it.

For all what you intend... maybe a proposal: Maybe its a option not to load the new objects using reflection but rather by storing instances of those objects and returning copies of the objects created using copy constructors or the clone method. In many cases this is less difficult to get running.

于 2012-04-04T21:54:45.303 回答
1

也许您正在寻找的是 Class.class ,例如:

Constructor constructor = aClass.getConstructor(new Class[]{String.class, Class.class});
于 2012-04-04T21:40:54.420 回答