使用包含参数的构造函数从类名创建Java对象

时间:2013-08-15 10:58:12

标签: java

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

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

adn我想做的事情:

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

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

4 个答案:

答案 0 :(得分: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 {

答案 1 :(得分: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);
}

答案 2 :(得分:1)

您需要在getConstructor中传递类型或参数才能获得正确的构造函数。尝试一下

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

intConstructor.newInstance(connectionSourceInstance, classInstance);

答案 3 :(得分:0)

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

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

有关详细信息,请参阅documentation of the getConstructor method

public Constructor<T> getConstructor(Class<?>... parameterTypes)
                              throws NoSuchMethodException,
                                     SecurityException