1.反射:在运行中,反射技术能知道任意一个类或者对象的所有属性和方法,并可以调用。
<1>获取反射类的三种方法
Class.forName(全限定类名);
类名.Class();
对象.getClass();
<2>获取反射类的方法
先获取反射类:Class<?> clazz = Class.forName(全限定类名);
实例化反射类:Person per = Class.forName(全限定类名).newInstance();
package Reflect;
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 TestReflect {
private Class<?> clazz;
@Test
public void test() {
//1.获取到反射类
try {
clazz = Class.forName("Reflect.Person");
//2.实例化反射类
Person per = (Person)clazz.newInstance();
//3.获取属性字段
Field name = clazz.getDeclaredField("name");
//4.操作实例对象的name属性
name.set(per, "王麻子");
System.out.println(per.name);
//5.获取方法字段
//调用公有方法
Method setAge = clazz.getDeclaredMethod("setAge",int.class);
//调用私有方法
Method eat = clazz.getDeclaredMethod("eat",null);
//6.调用实例化的方法
setAge.invoke(per, 15);
eat.setAccessible(true);
eat.invoke(per, null);
//7.获取构造方法
Constructor<?> constructor = clazz.getConstructor();
//8.通过构造函数创建对象
Person per1 = (Person) constructor.newInstance();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}