2。3。2Constructor类用于创建对象的方法 Student类同上一个示例,这里就不在重复提供了publicclassReflectDemo2{publicstaticvoidmain(String〔〕args)throwsClassNotFoundException,NoSuchMethodException,IllegalAccessException,InvocationTargetException,InstantiationException{TnewInstance(Object。。。initargs):根据指定的构造方法创建对象method1();method2();method3();method4();}privatestaticvoidmethod4()throwsClassNotFoundException,NoSuchMethodException,InstantiationException,IllegalAccessException,InvocationTargetException{获取一个私有的构造方法并创建对象1。获取class对象ClassclazzClass。forName(com。itheima。myreflect3。Student);2。获取一个私有化的构造方法。Constructorconstructorclazz。getDeclaredConstructor(String。class);被private修饰的成员,不能直接使用的如果用反射强行获取并使用,需要临时取消访问检查constructor。setAccessible(true);3。直接创建对象Studentstudent(Student)constructor。newInstance(zhangsan);System。out。println(student);}privatestaticvoidmethod3()throwsClassNotFoundException,InstantiationException,IllegalAccessException{简写格式1。获取class对象ClassclazzClass。forName(com。itheima。myreflect3。Student);2。在Class类中,有一个newInstance方法,可以利用空参直接创建一个对象Studentstudent(Student)clazz。newInstance();这个方法现在已经过时了,了解一下System。out。println(student);}privatestaticvoidmethod2()throwsClassNotFoundException,NoSuchMethodException,InstantiationException,IllegalAccessException,InvocationTargetException{1。获取class对象ClassclazzClass。forName(com。itheima。myreflect3。Student);2。获取构造方法对象Constructorconstructorclazz。getConstructor();3。利用空参来创建Student的对象Studentstudent(Student)constructor。newInstance();System。out。println(student);}privatestaticvoidmethod1()throwsClassNotFoundException,NoSuchMethodException,InstantiationException,IllegalAccessException,InvocationTargetException{1。获取class对象ClassclazzClass。forName(com。itheima。myreflect3。Student);2。获取构造方法对象Constructorconstructorclazz。getConstructor(String。class,int。class);3。利用newInstance创建Student的对象Studentstudent(Student)constructor。newInstance(zhangsan,23);System。out。println(student);}} 2。3。3小结 获取class对象 三种方式:Class。forName(全类名),类名。class,对象名。getClass() 获取里面的构造方法对象 getConstructor(C?。。。parameterTypes)getDeclaredConstructor(C?。。。parameterTypes) 如果是public的,直接创建对象 newInstance(Object。。。initargs) 如果是非public的,需要临时取消检查,然后再创建对象 setAccessible(boolean)暴力反射