Student类代码如下:
package ClassObjectPack;public class Student {private String name;int age;public String address;public Student(String name, int age, String address) {this.name = name;this.age = age;this.address = address;}public Student() {}private Student(String name) {this.name = name;}Student(String name, int age) {this.name = name;this.age = age;}private void function(){System.out.println("function");}public void method1(){System.out.println("method");}public void method2(String s){System.out.println("method:"+s);}public String method3(String s,int i){return s+","+i;}@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", age=" + age +", address='" + address + '\'' +'}';}}
代码如下:
package ClassObjectPack01;import java.lang.reflect.Constructor;import java.lang.reflect.InvocationTargetException;public class ReflectDemo01 {public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {Class<?> c = Class.forName("ClassObjectPack.Student");// public Student(String name, int age, String address)//Constructor<T> getConstructor(类<?>... parameterTypes)//返回一个 Constructor对象,该对象反映 Constructor对象表示的类的指定的公共 类函数。Constructor<?> con = c.getConstructor(String.class, int.class, String.class);// T newInstance(Object... initargs)// 使用此 Constructor对象表示的构造函数,使用指定的初始化参数来创建和初始化构造函数的声明类的新实例。Object obj = con.newInstance("林青霞", 30, "西安");System.out.println(obj);}}
测试结果:
代码如下:
package ClassObjectPack01;import java.lang.reflect.Constructor;import java.lang.reflect.InvocationTargetException;public class ReflectDemo02 {public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {Class<?> c = Class.forName("ClassObjectPack.Student");// private Student(String name)//Constructor<T> getConstructor(类<?>... parameterTypes)//返回一个 Constructor对象,该对象反映 Constructor对象表示的类的指定的公共 类函数。Constructor<?> con = c.getDeclaredConstructor(String.class);//我们无法通过私有构造创建对象// Object obj = con.newInstance("林青霞");// System.out.println(obj);//暴力反射//public void setAccessible (boolean flag):值为true,取消访问检查con.setAccessible(true);Object obj = con.newInstance("林青霞");System.out.println(obj);}}
测试结果: