2

我想从名称创建类对象,调用构造函数并创建新实例。但我不知道如何向构造函数发送参数。我的基类是:

    public carDao(ConnectionSource connectionSource, Class<Car> dataClass) throws SQLException 
{
    super(connectionSource, dataClass);
}

以及我想做的事情:

    Class myClass = Class.forName("carDao");
    Constructor intConstructor= myClass.getConstructor();
    Object o = intConstructor.newInstance();

我应该在 getConstructor() 中写什么?

4

4 回答 4

7

您需要为构造函数传递类

例如,如果您的构造函数有一个 String 参数

  Class myClass = Class.forName("carDao");
  Constructor<?> cons = myClass.getConstructor(String.class);
  Object o = cons.newInstance("MyString");

在您的情况下,它将是:

  myClass.getConstructor(ConnectionSource.class, Class.class);

由于 getConstructor 方法声明是这样的:

 //@param parameterTypes the parameter array
 public Constructor<T> getConstructor(Class<?>... parameterTypes)
    throws NoSuchMethodException, SecurityException {
于 2013-08-15T11:01:42.573 回答
3

这应该有效:

public static <T> T newInstance(final String className,final Object... args) 
        throws ClassNotFoundException, 
        NoSuchMethodException, 
        InstantiationException, 
        IllegalAccessException, 
        IllegalArgumentException, 
        InvocationTargetException {
  // Derive the parameter types from the parameters themselves.
  Class[] types = new Class[args.length];
  for ( int i = 0; i < types.length; i++ ) {
    types[i] = args[i].getClass();
  }
  return (T) Class.forName(className).getConstructor(types).newInstance(args);
}
于 2013-08-15T11:06:03.310 回答
1

您需要传入类型或参数getConstructor以获得正确的构造函数。试试吧

myClass.getConstructor(ConnectionSource.class,Class.class);

intConstructor.newInstance(connectionSourceInstance, classInstance);
于 2013-08-15T11:05:01.063 回答
0

您应该将Class对象提供给该getConstructor方法,如下所示:

Class myClass = Class.forName("carDao");
Constructor intConstructor= myClass.getConstructor(ConnectionSource.class, Class.class);
Object o = intConstructor.newInstance(connectionSource, dataClass);

有关更多信息,请参阅该方法的文档getConstructor

public Constructor<T> getConstructor(Class<?>... parameterTypes)
                              throws NoSuchMethodException,
                                     SecurityException
于 2013-08-15T11:04:56.233 回答