本帖最后由 赵太云 于 2013-7-20 22:46 编辑
如题,jdk提供的动态代理为要实现共同的接口??- package com.itheima;
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
- import java.lang.reflect.Proxy;
- public class Test {
- public static void main(String[] args) {
- //目标对象:
- final Target target = new Target();
-
- //代理对象:
- Object proxyObject =
- Proxy.newProxyInstance(
- target.getClass().getClassLoader(),
- target.getClass().getInterfaces(),
- new InvocationHandler() {
-
- @Override
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
-
- System.out.println("前置通知...");
-
- //调用目标的方法。
- Object retObject = method.invoke(target, args);
- System.out.println("后置通知...");
- return retObject;
- }
- });
- I i = (I) proxyObject;
- i.say();
- }
- }
- interface I{
- public void say();
- }
- class Target implements I{
- @Override
- public void say() {
- System.out.println("target........");
- }
- }
复制代码 |