欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  Java

java 动态代理的使用

程序员文章站 2022-04-21 21:44:54
...
1.接口Human.java
public interface Human {  
    void say();  
}

2.Human的实现类 Person

public class Person implements Human {  
  
    @Override  
    public void say() {  
        System.out.println("haha");  
    }  
  
}


3.处理类

import java.lang.reflect.InvocationHandler;  
import java.lang.reflect.Method;  
  
public class Hander implements InvocationHandler {  
    private Object obj;  
    public Hander(Object obj) {  
        this.obj = obj;  
    }  
    public Hander() {  
    }  
    @Override  
    public Object invoke(Object proxy, Method method, Object[] args)  
            throws Throwable {  
        System.out.println("before");  
        method.invoke(obj, args);  
        System.out.println("after");  
        return null;  
    }  
  
}


4. 使用

import java.lang.reflect.Proxy;  
  
public class Main {  
  
    public static void main(String[] args) {  
        // TODO Auto-generated method stub  
        Human i = (Human) Proxy.newProxyInstance(Thread.currentThread()  
                .getContextClassLoader(), Person.class.getInterfaces(),  
                new Hander(new Person()));  
        i.say();  
    }  
  
}


5. 输出结果

before  
haha  
after