【问题标题】:Creating Java object from class name with constructor, which contains parameters [duplicate]使用包含参数的构造函数从类名创建Java对象[重复]
【发布时间】:2013-08-15 10:58:12
【问题描述】:

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

    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() 中写什么?

【问题讨论】:

  • 这能回答你的问题吗 - stackoverflow.com/questions/6094575/…
  • 你应该首先解释为什么要使用反射,因为对于 99% 的问题,它是错误的解决方案。并尊重 Java 命名约定,并将您的类放在一个包中。
  • DAO 反模式,你不应该调用单例。
  • @RomanC 你在哪里看到单身人士?

标签: java


【解决方案1】:

你需要为你的构造函数传递类

例如,如果你的构造函数有一个字符串参数

  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 {

【讨论】:

【解决方案2】:

这应该可行:

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

【讨论】:

    【解决方案3】:

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

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

    intConstructor.newInstance(connectionSourceInstance, classInstance);
    

    【讨论】:

      【解决方案4】:

      您应该将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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-01
        • 2012-02-01
        • 2017-02-23
        • 2014-04-14
        • 2017-05-24
        • 1970-01-01
        • 1970-01-01
        • 2017-09-20
        相关资源
        最近更新 更多