在使用Java反射时,总是只记着:
Class.forName(className).newInstance()
那对构造函数带参数的Class又如何反射呢?
Class cls = Class.forName(className);
Class[] paramTypes = { String.class };
Object[] params = { "param" };
Constructor con = cls.getConstructor(paramTypes);
Bean bean = (Bean) con.newInstance(params);
接着就是方法的反射:
Class cls = Class.forName(classname) ;
Bean base = (Bean) cls.newInstance(); //获得该类的一个实例
Class[] paraTypes = new Class[]{ String.class };
Method method = cls.getMethod(fieldSetter, paraTypes);
String[] paravalues = new String[]{paraValue} ;
method.invoke(base, paravalues);