编写Java动态代理的步骤如下:
1.创建一个实现接口InvocationHandler的类,它必须实现invoke方法
2.创建被代理的类以及接口
3.通过Proxy的静态方法 newProxyInstance(ClassLoader loader, Class[] interfaces, InvocationHandler h)
4.通过代理调用方法
- package test;
- public interface PeopleInfac {
- public void showInfo();
- }
package test; public interface PeopleInfac { public void showInfo(); }
- package test;
- public class People implements PeopleInfac {
- public void showInfo() {
- System.out.println("people showInfo()");
- }
- }
package test; public class People implements PeopleInfac { public void showInfo() { System.out.println("people showInfo()"); } }
- package test;
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
- public class DanimacProxy implements InvocationHandler {
- Object o;
- public DanimacProxy(Object o) {
- this.o = o;
- }
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- method.invoke(o, null);
- return null;
- }
- }
package test; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class DanimacProxy implements InvocationHandler { Object o; public DanimacProxy(Object o) { this.o = o; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { method.invoke(o, null); return null; } }
- package test;
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Proxy;
- public class Test {
- public static void main(String[] args) {
- People p = new People();
- InvocationHandler proxy = new DanimacProxy(p);
- Class<?> cls = p.getClass();
- PeopleInfac pi = (PeopleInfac) Proxy.newProxyInstance(cls
- .getClassLoader(), cls.getInterfaces(), proxy);
- pi.showInfo();
- }
- }