反射
Reflection(反射)是被视为动态语言的关键,反射机制允许程序在执行期借助于Reflection API取得任何类的内部信息,并能直接操作任意对象的内部属性及方法。
加载完类之后,在堆内存的方法区中就产生了一个Class类型的对象(一个类只有一个Class对象),这个对象就包含了完整的类的结构信息。我们可以通过这个对象看到类的结构。这个对象就像一面镜子,透过这个镜子看到类的结构,所以,我们形象的称之为:反射。
Java反射机制提供的功能
在运行时判断任意一个类所属的类
在运行时构造任意一个类的对象
在运行时判断任意一个类具有的成员变量和方法
在运行时获取泛型信息
在运行时调用任意一个对象的成员变量和方法
在运行时处理注解
生成动态代理
反射的使用
public class ReflectionTest {
@Test
public void test() throws Exception {
// 使用反射之前需要通过构造器new类的对象
// 通过对象调用其内部属性方法
Person p1 = new Person("gyq", 18, 100.1);
// 不能调用其私有的属性,方法,构造器
System.out.println(p1.name);
System.out.println(p1.toString());
System.out.println("-------------");
// 通过反射对Person的操作
Class clazz = Person.class;
// 通过反射创建Person类的对象
Constructor constructor = clazz.getConstructor(String.class, int.class, double.class);
Object obj = constructor.newInstance("NONAME", 10, 88.8);
Person p2 = (Person) obj;
System.out.println(p2.toString());
// 通过反射调用对象公开的属性方法
Field score = clazz.getDeclaredField("name");
score.set(p2, "gaiming");
System.out.println(p2);
Method show = clazz.getDeclaredMethod("show");
show.invoke(p2);
System.out.println("------------");
// 通过反射调用对象私有的结构
// 私有构造器
Constructor constructor1 = clazz.getDeclaredConstructor(String.class);
constructor1.setAccessible(true);
Person p3 = (Person) constructor1.newInstance("xinren");
System.out.println(p3);
// 调用私有的属性
Field age = clazz.getDeclaredField("age");
Field score1 = clazz.getDeclaredField("score");
age.setAccessible(true);
score1.setAccessible(true);
age.set(p3, 20);
score1.set(p3, 99.99);
System.out.println(p3);
//调用私有的方法
Method showScore = clazz.getDeclaredMethod("showScore", String.class);
showScore.setAccessible(true);
showScore.invoke(p3, "77.7");
}
}
class Person {
public String name;
private int age;
private double score;
public void setAge(int age) {
this.age = age;
}
public void setScore(double score) {
this.score = score;
}
private Person(String name) {
this.name = name;
}
public Person(String name, int age, double score) {
this.name = name;
this.age = age;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public double getScore() {
return score;
}
public void show() {
System.out.println("我叫:" + name + ",今年" + age + "岁,我考了:" + score + "分!");
}
private void showScore(String score) {
System.out.println("我考了:" + score);
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", score=" + score +
'}';
}
}
获取Class的实例的方式
public class ReflectionTest {
@Test
public void test() throws ClassNotFoundException {
//获取Class实例的四种方式,前三种需要掌握
//方式一:调用运行时类的属性:.class
Class<Person> clazz1 = Person.class;
System.out.println(clazz1);
//方式二:通过运行时类的对象
Person p1 = new Person("GYQ", 8, 10.0);
Class clazz2 = p1.getClass();
System.out.println(clazz2);
//方式三:调用Class的静态方法:forName(String classPath) 全类名
Class clazz3 = Class.forName("com.example.base.Person");
System.out.println(clazz3);
//判断获取到的Class对象是不是同一个
System.out.println(clazz1 == clazz2);
System.out.println(clazz1 == clazz3);
//方式四:使用类的加载器ClassLoader
ClassLoader classLoader = ReflectionTest.class.getClassLoader();
Class clazz4 = classLoader.loadClass("com.example.base.Person");
System.out.println(clazz4);
System.out.println(clazz1 == clazz4);
}
}
对于java.lang.Class类的理解
类的加载过程:
程序经过javac.exe命令之后,会生成一个或多个字节码文件(.class结尾)。接着我们使用java.exe命令对某个字节码文件进行解释运行,相当于将某个字节码文件加载到内存中,此过程就称为类的加载。
加载到内存中的类,我们就称为运行时类,此运行时类,就作为Class的一个实例。
换句话说:Class的实例就对应着一个运行时类。
加载到内存中的运行时类会缓存一定的时间,在此时间之内,我们可以通过不同的方式来获取此运行实例
哪些类型可以有Class对象?
数组的元素类型与维度相同则是同一个Class,如(int[100] 和 int[10])
类加载过程
ClassLoader的理解
public class ClassLoaderTest {
@Test
public void test() {
//获取当前自定义类的加载器 系统类加载器
ClassLoader classLoader = ClassLoaderTest.class.getClassLoader();
System.out.println(classLoader);
//调用系统类加载器的getParent()获得模块加载器
//注意:原来的扩展类加载器在jdk9之后被移除,由模块加载器代替
ClassLoader classLoader1 = classLoader.getParent();
System.out.println(classLoader1);
//调用模块加载器的getParent():无法获取引导类加载器 结果:null
//引导类加载器主要负责加载java的核心类库,无法加载自定义类
ClassLoader classLoader2 = classLoader1.getParent();
System.out.println(classLoader2);
//结果也为null,说明String是由引导类加载器加载的,无法获取到
ClassLoader classLoader3 = String.class.getClassLoader();
System.out.println(classLoader3);
}
}
使用ClassLoader加载配置文件
public class ClassLoaderTest {
@Test
public void test() throws Exception {
Properties pros = new Properties();
//读取配置文件的方式一
//此时文件默认在当前module下。
// FileInputStream fis = new FileInputStream("jdbc.properties");
// pros.load(fis);
//读取配置文件的方式二
//此时文件默认在src下,若为动态web工程则在resources下
ClassLoader classLoader = ClassLoaderTest.class.getClassLoader();
InputStream is = classLoader.getResourceAsStream("jdbc.properties");
pros.load(is);
String user = pros.getProperty("user");
String password = pros.getProperty("password");
System.out.println("user=" + user + " password=" + password);
}
}
反射的用法
通过反射创建运行时类的对象
//通过反射创建对应的运行时类的对象
@Test
public void test() throws Exception {
Class<Person> clazz = Person.class;
//获取运行时类的构造器
Constructor<Person> constructor = clazz.getDeclaredConstructor();
Person p1 = constructor.newInstance();
System.out.println(p1);
}
反射的动态性
@Test
public void test() throws Exception {
//获取范围在[0,3)的随机整数
int number = new Random().nextInt(3);
String classPath = "";
switch (number) {
case 0:
classPath = "java.util.Date";
break;
case 1:
classPath = "java.lang.String";
break;
case 2:
classPath = "com.example.base.Person";
break;
}
Object instance = getInstance(classPath);
System.out.println(instance.getClass());
}
//创建指定类的对象 classPath:指定类的全类名
public Object getInstance(String classPath) throws Exception {
Class clazz = Class.forName(classPath);
Constructor constructor = clazz.getConstructor();
return constructor.newInstance();
}
获取运行时类的属性
@Test
public void test() throws Exception {
Class clazz = Class.forName("com.example.base.Person");
//获取当前运行时类及其父类中声明public的访问权限的属性
Field[] fields1 = clazz.getFields();
for (Field field : fields1) {
System.out.println(field);
}
System.out.println("----------");
//获取当前运行时类自己的所有的属性
Field[] declaredFields = clazz.getDeclaredFields();
for (Field field : declaredFields) {
System.out.println(field);
}
System.out.println("----------");
//分别获取当前运行时类的属性的权限修饰符,数据类型,变量名
//0代表default,1代表public,2代表private
//可以用Modifier.toString()返回指定数字代表的权限
Field[] declaredFields1 = clazz.getDeclaredFields();
for (Field field : declaredFields1) {
System.out.println(Modifier.toString(field.getModifiers()));
System.out.println(field.getType());
System.out.println(field.getName());
System.out.println();
}
}
获取运行时类的方法及其内部结构
@Test
public void test() throws Exception {
Class clazz = Person.class;
//获取运行时类及其子类的所有声明为public的方法
Method[] methods = clazz.getMethods();
for (Method m : methods) {
System.out.println(m);
}
System.out.println("-------------");
//获取当前运行时类的所有方法
Method[] declaredMethods = clazz.getDeclaredMethods();
for (Method dm : declaredMethods) {
System.out.println(dm);
}
System.out.println("-------------");
//获取运行时类的方法的内部结构
/* @XXX
权限修饰符 返回值类型 方法名(参数类型1,形参名,...) throws XxxException{};
*/
for (Method dm : declaredMethods) {
//获取方法声明的注解
Annotation[] annotations = dm.getAnnotations();
for (Annotation annotation : annotations) {
System.out.print("注解:" + annotation + "\t");
}
//获取方法的权限修饰符
int modifiers = dm.getModifiers();
System.out.print("权限修饰符:" + Modifier.toString(dm.getModifiers()) + "\t");
//获取方法的返回值类型
System.out.print("返回值类型:" + dm.getReturnType().getName() + "\t");
//获取方法的方法名
System.out.print("方法名:" + dm.getName() + "\t");
//获取方法形参列表
System.out.print("形参列表:");
Class[] parameterTypes = dm.getParameterTypes();
for (Class parameterType : parameterTypes) {
System.out.print(parameterType.getName());
}
//抛出的异常
System.out.print("异常:");
Class[] exceptionTypes = dm.getExceptionTypes();
for (Class exceptionType : exceptionTypes) {
System.out.print(exceptionType.getName());
}
System.out.println();
}
}
获取运行时类的构造器
@Test
public void test() throws Exception {
Class<Person> clazz = Person.class;
//获取当前运行时类中声明为public的构造器
Constructor[] constructors = clazz.getConstructors();
for (Constructor constructor : constructors) {
System.out.println(constructor);
}
System.out.println("------------");
//获取当前运行时类的所有构造器
Constructor[] declaredConstructors = clazz.getDeclaredConstructors();
for (Constructor declaredConstructor : declaredConstructors) {
System.out.println(declaredConstructor);
}
}
获取运行时类的父类及父类的泛型
@Test
public void test() throws Exception {
Class clazz = Person.class;
//获取当前运行时类的父类
System.out.println(clazz.getSuperclass());
//获取带泛型的父类
Type genericSuperclass = clazz.getGenericSuperclass();
System.out.println(genericSuperclass);
//获取泛型类型
ParameterizedType paramType = (ParameterizedType) genericSuperclass;
Type[] actualTypeArguments = paramType.getActualTypeArguments();
System.out.println(((Class)actualTypeArguments[0]).getName());
}
获取运行时类或其父类的接口,运行时类所在的包,注解
@Test
public void test() throws Exception {
Class clazz = Person.class;
//获取当前运行时类实习的接口
Class[] interfaces = clazz.getInterfaces();
for (Class anInterface : interfaces) {
System.out.println(anInterface);
}
//获取当前运行时类的父类实现的接口
Class[] interfaces1 = clazz.getSuperclass().getInterfaces();
for (Class anInterface : interfaces1) {
System.out.println(anInterface);
}
//获取当前运行时类所在的包
Package aPackage = clazz.getPackage();
System.out.println(aPackage);
//当前运行时类声明的注解
Annotation[] annotations = clazz.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
}
调用运行时类的,属性,方法构造器
//调用运行时类的对象
@Test
public void test() throws Exception {
Class clazz = Person.class;
Person p = (Person) clazz.newInstance();
System.out.println(p);
//获取指定的属性
Field score = clazz.getDeclaredField("score");
//若属性为私有属性则需要设置属性为可访问的
score.setAccessible(true);
//设置指定对象的指定属性值
score.set(p, 59.9);
System.out.println(p);
//获取指定对象的指定属性值
Double pScore = (Double) score.get(p);
System.out.println(pScore);
}
//调用运行时类的方法
@Test
public void test1() throws Exception {
Class<Person> clazz = Person.class;
Person p = (Person) clazz.newInstance();
//获取指定的方法 指明方法名,形参列表
Method showScore = clazz.getDeclaredMethod("showScore", String.class);
//若方法为私有,需要保证当前方法可访问
showScore.setAccessible(true);
//调用指定方法,指明调用者,形参 invoke方法的返回值,即为被调用方法的返回值
String score = (String) showScore.invoke(p, "88.0");
System.out.println(score);
//调用运行时类的静态方法
Method readBook = clazz.getDeclaredMethod("readBook");
readBook.setAccessible(true);
//通过类调用,也可以写null
int page = (int) readBook.invoke(Person.class);
System.out.println(page);
}
//调用运行时类的构造器
@Test
public void test2() throws Exception {
Class clazz = Class.forName("com.example.base.Person");
//获取指定构造器 参数是形参的.class
Constructor constructor = clazz.getDeclaredConstructor(String.class, int.class, double.class);
constructor.setAccessible(true);
Person p = (Person) constructor.newInstance("GYQ", 12, 88.8);
System.out.println(p);
}
反射的应用
动态代理
代理设计模式的原理:
使用一个代理将对象包装起来,然后用该代理对象取代原始对象。任何对原始对象的调用都要通过代理。代理对象决定是否以及合适将方法调用转到原始对象上。
之前学到的代理机制(见笔记 面向对象(下))属于静态代理,特征是代理类和目标对象的类都是在编译期间确定下来,不利于程序的扩展,同时每个代理类只能为一个接口服务,这样依赖程序开发中必然产生过多的代理。最好可以通过一个代理类完成全部的代理功能。
动态代理
动态代理是指客户通过代理类来调用其他对象的方法,并且是在程序运行时根据需要动态创建目标类的代理对象。
动态代理的使用场合:调试,远程方法调用
相较于静态代理的优点:
抽象角色中(接口)声明的所有方法都被转移到调用处理器一个集中的方法中处理,这样,我们可以更加灵活和统一的处理众多的方法。
静态代理例:
public class StaticProxyTest {
@Test
public void test() {
//创建被代理类对象
HLSFoodFactory foodFactory = new HLSFoodFactory();
//创建代理类对象
ProxyFoodFactory proxyFoodFactory = new ProxyFoodFactory(foodFactory);
//调用代理类方法
proxyFoodFactory.produceFood();
}
}
interface FoodFactory {
void produceFood();
}
//代理类
class ProxyFoodFactory implements FoodFactory {
private FoodFactory foodFactory;//用被代理类进行实例化
public ProxyFoodFactory(FoodFactory foodFactory) {
this.foodFactory = foodFactory;
}
@Override
public void produceFood() {
System.out.println("代理工厂准备工作");
foodFactory.produceFood();
System.out.println("代理工厂收尾工作");
}
}
//被代理类
class HLSFoodFactory implements FoodFactory {
@Override
public void produceFood() {
System.out.println("工厂开始做饭");
}
}
要想实现动态代理需要解决的问题?
问题一:如何根据加载到内存中的被代理类,动态的创建代理类及其对象。
问题二:当通过代理类的对象调用方法时,如何动态的调用被代理类中的同名方法。
动态代理例:
public class ProxyTest {
public static void main(String[] args) {
SuperMan superMan = new SuperMan();
Human proxtInstance = (Human) ProxyFactory.getProxtInstance(superMan);
proxtInstance.eat("鸡腿");
String belief = proxtInstance.getBelief();
System.out.println(belief);
System.out.println("--------------");
Factory factory = new Factory();
Maker proxtInstance1 = (Maker) ProxyFactory.getProxtInstance(factory);
proxtInstance1.makeproducts();
}
}
//这样定义为了更形象,易于理解。实际上接口应该是定义的规范
interface Human {
String getBelief();
void eat(String food);
}
interface Maker {
void makeproducts();
}
//被代理类1
class SuperMan implements Human {
@Override
public String getBelief() {
return "I believe i can fly!";
}
@Override
public void eat(String food) {
System.out.println("超人喜欢吃" + food);
}
}
//被代理类2
class Factory implements Maker {
@Override
public void makeproducts() {
System.out.println("工厂生产产品");
}
}
class ProxyFactory {
//获取代理类的对象 解决第一个问题 obj是被代理类的对象
public static Object getProxtInstance(Object obj) {
MyInvocationHandler handler = new MyInvocationHandler();
handler.bind(obj);
return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), handler);
}
}
class MyInvocationHandler implements InvocationHandler {
private Object obj;//赋值时使用被代理类的对象进行赋值
public void bind(Object obj) {
this.obj = obj;
}
//当我们通过代理类的对象调用方法a时,就会自动的调用如下方法
//将被代理类要执行的方法a的功能声明在invoke方法中
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//method即为代理类对象调用的方法,此方法也就作为了被代理类要调用的方法
//obj:被代理类的对象
Object returnValue = method.invoke(obj, args);
return returnValue;
}
}