package com.ruqi.xiushifu.method;
// 作为被代理的对象,需要实现接口类
public class Star implements Skill{
@Override
public void run() {
System.out.println("对象本身的逻辑,run");
}
@Override
public void jump() {
System.out.println("对象本身的逻辑,jump");
}
}
=======================================
package com.ruqi.xiushifu.method;
public interface Skill {
void run();
void jump();
}
=======================================
实现代理逻辑
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class GetAgentProxy {
public static Skill gtAgentProxy(Star obj){
/**
* (ClassLoader loader, 类加载器,固定写法
* Class<?>[] interfaces, 添加被代理的接口实现
* InvocationHandler h) , 代理的实际操作
*/
return (Skill) Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),
new InvocationHandler() {
// method 表示代理时调用的方法,通过反射进行调用,args表示方法添加的参数
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("代理前置操作");
Object rs = method.invoke(obj, args);
System.out.println("代理后置操作");
return rs;
}
});
}
}
====================================
调用代理逻辑
public class Test {
public static void main(String[] args) {
Star s = new Star();
Skill sk = GetAgentProxy.gtAgentProxy(s); //获取代理对象
sk.jump();
sk.run();
}
}
通用的代理方法,传入目标对象即可
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class GetProxy {
public static Object getProxyObject(Object taget){
ClassLoader classLoader = taget.getClass().getClassLoader();
Class<?>[] interfaces = taget.getClass().getInterfaces();
InvocationHandler invocationHandler = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("代理前一步");
Object obj = method.invoke(taget, args);
System.out.println("代理后一步");
return obj;
}
};
return Proxy.newProxyInstance(classLoader,interfaces,invocationHandler);
}
}
=================================
public class Testcase {
public static void main(String[] args) {
InterfaceTool proxyObject = (InterfaceTool)GetProxy.getProxyObject(new InterfacetoolImpl());
proxyObject.add(1, 2);
}
}