1 使用newInstance(),实际上是调用运行时空参的构造器
注意构造器的权限修饰符要足够,同时必须有一个空参的构造器。
2 调用指定的属性方法构造器
package lianxi1; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.junit.Test; public class TestReflection2 { @Test public void test1() throws ClassNotFoundException, SecurityException, NoSuchFieldException, InstantiationException, IllegalAccessException { //1.获取运行类的属性 String str = "lianxi1.Person"; Class clazz = Class.forName(str); Field f1 = clazz.getField("name"); //如果属性是private的 Field f2 = clazz.getDeclaredField("age"); f2.setAccessible(true); //2.创建运行类的对象 Object obj = clazz.newInstance(); Person p = (Person)obj; System.out.println(p); //3.对属性赋值 f1.set(p, "tian"); f2.set(p, 25); System.out.println(p); } @Test public void test2() throws ClassNotFoundException, SecurityException, NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{ //2.调用运行时类中指定的方法 Class clazz = Person.class; Method m1 = clazz.getMethod("show"); Person p1 = (Person)clazz.newInstance(); Object obj = m1.invoke(p1); //如果是静态方法改为 m1.invoke(Person.class) System.out.println(obj); Method m2 = clazz.getDeclaredMethod("display",String.class,int.class); m2.setAccessible(true); Object obj2 = m2.invoke(p1,"yu",22); System.out.println(obj2); } @Test public void test3() throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException{ //3.调用制定的构造器,创建运行时类的对象 Class clazz = Person.class; Constructor con = clazz.getDeclaredConstructor(String.class,int.class); con.setAccessible(true); Person p2 = (Person)con.newInstance("wuming",21); System.out.println(p2); } }