代码如下:
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;
import java.lang.reflect.Method;public class ReflectDemo06 {public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {Class<?> c = Class.forName("ClassObjectPack.Student");Constructor<?> con = c.getConstructor();Object obj = con.newInstance();Method m1 = c.getMethod("method1");m1.invoke(obj);Method m2 = c.getMethod("method2", String.class);m2.invoke(obj,"林青霞");Method m3 = c.getMethod("method3", String.class, int.class);Object o = m3.invoke(obj, "林青霞", 30);System.out.println(o);// Method m4 = c.getMethod("function");Method m4 = c.getDeclaredMethod("function");m4.setAccessible(true);m4.invoke(obj);System.out.println(m4);}
}
测试结果: