通过反射构造对象
1、先创建一个对象,必须有构造器,这边创了一个有参构造器和无参构造器
class Student{ private int age; public void study(String[] arr){ System.out.println(arr[0]+",age:"+age); } public Student() { } public Student(int age) { this.age = age; } }
2、先得到类的class,再通过class得到构造器,这边创的是有参构造器
Student student=null; try { Constructor constructor=Student.class.getConstructor(int.class); student=(Student) constructor.newInstance(2); } catch (Exception e) { e.printStackTrace(); } student.study(new String[]{"飞","扬"});
3、运行