0

I have been reading some where, but i can't find the best solution, they are using

Class tempClass = Class.forName(classname);
Constructor constructor = tempClass.getDeclaredConstructor(String.class);

they define their params type, but how if the tempClass is dynamic, of course they have different constructor params right?

is there any workaround to solve this problem?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
  • If you don't know the parameters of the constructor you're looking for, you can iterate through `tempClass.getDeclaredConstructors()`. – Andy Turner Sep 24 '17 at 12:28
  • Can you give an example of what you mean by "the tempClass is dynamic"? – EJK Sep 24 '17 at 14:23

2 Answers2

2

You need to overload your constructor with the parameters of type you are expecting. This is known as compile time polymorphism. For example you want your constructor to handle int float and char parameters. You will need to overload your constructor with these parameters. So that it can handle different params dynamically.

Example:
    Constructor(int a, int b);
    Constructor(char a, char b);
    Constructor(float a, float b);
Umar Tahir
  • 585
  • 6
  • 21
1

Look at how getDeclaredConstructors() is defined:

public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)

The Class<?>... notation means that the method is variadic. It takes a list of Class objects as arguments, and there are two ways to provide that list:

  1. You can list the objects as separate arguments:

    Constructor<?> ctor = getDeclaredConstructor(String.class, String.class, Integer.class, etc)
    
  2. You can construct an array and pass the array as a single argument

    Class<?>[] classes = new Class<?>[3];
    classes[0] = String.class;
    ...
    Constructor<?> ctor = getDeclaredConstructor(classes);
    

To find a constructor without knowing ahead of time how many parameters it has or what their types are, you'd use the second method--construct an array describing the parameter list that you're looking for, then call getDeclaredConstructor() with that array as a parameter. Here's an example:

static <T> T construct(Class<T> aClass, Object...args)
        throws NoSuchMethodException, SecurityException,
        InstantiationException, IllegalAccessException,
        IllegalArgumentException, InvocationTargetException {
    Class<?>[] classes = new Class<?>[args.length];
    for (int ii = 0; ii < args.length; ++ii) {
        classes[ii] = args[ii].getClass();
    }

    Constructor<T> ctor = aClass.getDeclaredConstructor(classes);
    return ctor.newInstance(args);
}
...
String abc = construct(String.class, "abc");
URL google = construct(URL.class, "http", "google.com", "/");
Kenster
  • 23,465
  • 21
  • 80
  • 106