Java-反射
承灿 2023/7/7
# Java程序是如何运行的?
# Java-反射机制
# 1 定义
在程序运行时动态的获取类的信息,包括但不限于类的属性、方法、构造函数等
且能操作类的成员和调用方法
# 2 核心类
# Class 运行时可以获取类、接口的信息
# Constructor 类的构造函数,用来创建类的实例
# Method 来调用类的方法
# Field 读取或修改类的字段值
动态实例化对象
Class<?> clazz = MyClass.class;
Object instance = clazz.newInstance();
调用类的静态方法
Method method = clazz.getMethod("staticMethod", int.class);
method.invoke(null, 10);
获取类的字段值
Field field = clazz.getDeclaredField("fieldName");
field.setAccessible(true);
Object value = field.get(instance);
# 3 具体的使用
package com.example.reflection.handler;
import com.example.reflection.service.MyClass;
import com.example.reflection.service.impl.MyClassImpl;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
class MyInvocationHandler implements InvocationHandler {
private MyClass myClass;
public MyInvocationHandler(MyClass myClass) {
this.myClass = myClass;
}
public MyInvocationHandler() {
}
public Object invoke(Object proxy, Method method, Object[] args) throws InvocationTargetException, IllegalAccessException {
// 在代理对象上调用方法前的操作
System.out.println("在代理对象上调用方法前的操作========");
Object result = method.invoke(myClass, args);
System.out.println("在代理对象上调用方法前的操作========");
// 在代理对象上调用方法后的操作
return result;
}
public static void main(String[] args) throws ClassNotFoundException {
//实际被代理的对象
MyClass myClass1 = new MyClassImpl();
//拦截器
MyInvocationHandler myInvocationHandler = new MyInvocationHandler(myClass1);
//获取类信息
Class<?> aClass = Class.forName("com.example.reflection.service.MyClass");
//进行动态代理 获取类的实例(类加载器,实际被代理的类对象,拦截器)
MyClass instance = (MyClass) Proxy.newProxyInstance(aClass.getClassLoader(), new Class[]{aClass}, myInvocationHandler);
instance.test("海王唐智科", 38);
}
}
package com.example.reflection.service;
/**
* @author lichengcan
*/
public interface MyClass {
void test(String name,Integer age);
}
package com.example.reflection.service.impl;
import com.example.reflection.service.MyClass;
/**
* @author: lichengcan
* @date: 2023-07-09 09:47
* @description
**/
public class MyClassImpl implements MyClass {
@Override
public void test(String name, Integer age) {
System.out.println("我叫 : " + name+",今年"+age+"岁。");
}
}