vendredi 25 août 2017

Reflection - Getting New Instance of unknown classes with unknown number of constructor parameters

First of all, I am new to Reflection. I have been working on a large project and I needed to use reflection on some parts (Yes I definitely need it). So I thought, I should create a Reflection Helper class which will be able to create new instances of any class with any number of parameters within my project.

As an example to my question: Normally(as far as I know), to create an instance of a class which has 2 strings as parameters in its constructor;

Class.getConstructor(String.class, String.class).newInstance("Arg_1", "Args_2");

will do the job. However, in my case I need a method which will work for any class with any constructor. So I created these methods but it doesn't seem to work, I keep getting NoSuchMethodException. I need help at making it work.

private static String packagePrefix = "com.***";

@SuppressWarnings("rawtypes")
public static Class getClass(String className) throws ClassNotFoundException {
    return Class.forName(packagePrefix + "." + className);
}

@SuppressWarnings({ "rawtypes", "unchecked" })
public static Object getClassInstance(String className, Object... args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
    Class[] cArgs = new Class[args.length];
    for (int i = 0; i < args.length; i++) {
        cArgs[i] = args[i].getClass();
    }
    return getClass(className).getConstructor(cArgs).newInstance(args);
}





Aucun commentaire:

Enregistrer un commentaire