首先要有一個接口
java
public interface SayHello { public void sayHello(); }
其次要有一個接口的實現類
ide
public class SayHelloImp implements SayHello { @Override public void sayHello() { System.out.println("hello world!"); } }
要有一個代理類
代理類主要注意兩點一個是要實現invocationHandler該接口,其次就是對Proxy.newInstance();方法的調用
this
public class MyProxy implements InvocationHandler { private Object obj; private void before() { System.out.println("before"); } private MyProxy(Object ob) { obj = ob; } private void after() { System.out.println("after"); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object reObject; before(); reObject = method.invoke(this.obj, args); after(); return reObject; } public static Object getInstance(Object ob) { return Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), ob .getClass().getInterfaces(), new MyProxy(ob)); } }
最後是main方法
spa
public static void main(String[] args) { SayHello hello = (SayHello) MyProxy.getInstance(new SayHelloImp()); hello.sayHello(); }