2

I want to create class object from name, call constructor and create new instance. But I don't know how to send parameters to constructor. My base class is:

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

adn what i want do do:

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

what should I write in getConstructor()?

user2086174
  • 195
  • 1
  • 3
  • 12

4 Answers4

7

You need to pass classes for your constructor

For example if your constructor has a String parameter

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

In your case it will be:

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

Since getConstructor method declaration is this:

 //@param parameterTypes the parameter array
 public Constructor<T> getConstructor(Class<?>... parameterTypes)
    throws NoSuchMethodException, SecurityException {
Tala
  • 8,888
  • 5
  • 34
  • 38
3

This should work:

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);
}
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
1

You need to pass types or arguments in getConstructor to get correct constructor. Try maybe

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

and

intConstructor.newInstance(connectionSourceInstance, classInstance);
Pshemo
  • 122,468
  • 25
  • 185
  • 269
0

You should give the Class objects to the getConstructor method, like this:

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

For more information, refers to the documentation of the getConstructor method:

public Constructor<T> getConstructor(Class<?>... parameterTypes)
                              throws NoSuchMethodException,
                                     SecurityException
LaurentG
  • 11,128
  • 9
  • 51
  • 66