jdk代理

xiaoxiao2021-02-28  51

jdk代理

    解释:程序在运行过程中,根据被代理的接口来动态生成代理类的class文件,并且加载运行。     JDK提供了java.lang.reflect.Proxy类来实现动态代理的,可通过它的newProxyInstance来获得代理实现类。 1:自定义接口 package javabase.allinterface; public interface SaySimple { void sayHelloForSomeone(String name); }2:接口实现类 package javabase.allimpl; import javabase.allinterface.SaySimple; public class SaySimpleImpl01 implements SaySimple{ @Override public void sayHelloForSomeone(String name) { System.out.println("Hello!"+name); } } 3:自定义实现InvocationHandler接口的类 package javabase; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class ImplInvocationHandler implements InvocationHandler { private Object targetObj; public ImplInvocationHandler(Object obj) { this.targetObj = obj; } /** * @return * GY * 2017年11月6日 */ public Object getProxy(){ return java.lang.reflect.Proxy.newProxyInstance(targetObj.getClass().getClassLoader(), targetObj.getClass().getInterfaces(), new ImplInvocationHandler(targetObj)); } /* * * */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("Before invocation"); Object retVal = method.invoke(targetObj, args); System.out.println("After invocation"); return retVal; } } 4:测试,用代理对象执行被代理接口实现类的方法 package javabase; import java.lang.reflect.Proxy; import javabase.allimpl.SaySimpleImpl01; import javabase.allinterface.SaySimple; public class TestOfInvocationHandler { public static void main(String[] args) { SaySimple s = new SaySimpleImpl01(); ImplInvocationHandler handle = new ImplInvocationHandler(s); SaySimple proxy = (SaySimple)Proxy.newProxyInstance(//TestOfInvocationHandler.class.getClassLoader(), handle.getClass().getClassLoader(), //new Class[]{SaySimple.class}, s.getClass().getInterfaces(), handle); proxy.sayHelloForSomeone("GY"); SaySimple proxy2 = (SaySimple)handle.getProxy(); proxy2.sayHelloForSomeone("WX"); } }
转载请注明原文地址: https://www.6miu.com/read-1000149.html

最新回复(0)