Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /wmcuit/data/www/wmcuit.com/wp-content/plugins/wp-syntax/wp-syntax.php on line 383
Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /wmcuit/data/www/wmcuit.com/wp-content/plugins/wp-syntax/wp-syntax.php on line 383
遇到一个关于反射具有数组参数的类问题,通过查阅JDK文档,终于解决了,兴奋~~~
Class<T>类、Constructor<T>类,需要好好理解其作用。
某个类可以通过其 bject.getConstructor 获取该类的构造方法,再用(Constructor)c.newInstance([参数数组]),来完成一个类的实例化。
说明:
newInstance的参数必需是Object[],这个数组是不定长的。
例一:
非数组参数
1 2 3 4 5 6 | public Role(String name,String sex,int age){} Constructor< ? extends Role> constructor = inCmdClass.getConstructor(String.class,String.class,Integer.class); Role role = constructor.newInstance(new Object[]{”wangming”,”male”,23}); role.getName();//wangming role.getSex();//male role.getAge();//23 |
例二:
数组参数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | public class TestReflect { public TestReflect(String name,String sex,String[] books){ System.out.println(name + ":" + sex +":" +books.length); } public TestReflect(String[] books){ System.out.println(books.length); } /** * @param args * @throws NoSuchMethodException * @throws SecurityException * @throws InvocationTargetException * @throws IllegalAccessException * @throws InstantiationException * @throws IllegalArgumentException */ public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { System.out.println("~~~~~~~~~~~c1~~~~~~~~~~~~"); Constructor< ? extends TestReflect> c1 = TestReflectOne.class.getConstructor(String.class,String.class,String[].class); c1.newInstance("wang","male",args); System.out.println("~~~~~~~~~~~c2~~~~~~~~~~~~"); Constructor< ? extends TestReflect> c2 = TestReflectOne.class.getConstructor(String.class,String.class,String[].class); c2.newInstance(new Object[]{"wang","male",args}); System.out.println("~~~~~~~~~~~c3~~~~~~~~~~~~"); Constructor< ? extends TestReflect> c3 = TestReflectOne.class.getConstructor(new Class[]{String.class,String.class,String[].class}); c3.newInstance(new Object[]{"wang","male",args}); System.out.println("~~~~~~~~~~~c4~~~~~~~~~~~~"); Constructor< ? extends TestReflect> c4 = TestReflectOne.class.getConstructor(String[].class); c4.newInstance(new Object[]{args});//这里必需要这样写 } } public class TestReflectOne extends TestReflect { public TestReflectOne(String name, String sex, String[] books) { super(name, sex, books); System.out.println("TestReflectOne"); } public TestReflectOne(String[] books) { super(books); System.out.println("TestReflectOne"); } } |