标签:ade 实现类 使用 class override 调用接口 package interface oca
一、使用jdk自带的动态代理机制:
package aopdemo.jdk; public interface INormalService { public void service(); }
package aopdemo.jdk; public class NormalServiceImpl implements INormalService { @Override public void service() { System.out.println("invoke service"); } }
package aopdemo.jdk; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class MyInvocationHandler implements InvocationHandler { Object target; public MyInvocationHandler(Object target) { this.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("before service"); Object object = method.invoke(target, args); System.out.println("after service"); return object; } }
package aopdemo.jdk; import java.lang.reflect.Proxy; public class JdkProxyDemo { public static void main(String[] args) { INormalService normalService = new NormalServiceImpl(); MyInvocationHandler handler = new MyInvocationHandler(normalService); INormalService iNormalService = (INormalService) Proxy .newProxyInstance(normalService.getClass().getClassLoader(), normalService.getClass().getInterfaces(), handler); iNormalService.service(); } }
执行结果为:
before service
invoke service
after service
标签:ade 实现类 使用 class override 调用接口 package interface oca
原文地址:https://www.cnblogs.com/silenceshining/p/11129688.html