JDK动态代理是基于接口的代理,下面举例说明ide
首先说明下InvocationHandler的invokethis
public interface InvocationHandler {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable;
}
proxy:方法基于哪一个proxy实例来执行spa
method:执行proxy实例的哪一个方法(proxy代理谁就执行谁的方法)代理
args:methed的入参code
代码示例:blog
public interface Say { void sayHello(String words); }
public class SayImpl implements Say { @Override public void sayHello(String words) { System.out.println("hello:" + words); } }
public class TestInvocationHandler implements InvocationHandler { private Object target; public TestInvocationHandler(Object target) { this.target=target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("invoke begin"); System.out.println("method :"+ method.getName()+" is invoked!"); method.invoke(target,args); System.out.println("invoke end"); return null; } }
public static void main(String[] args) { TestInvocationHandler testInvocationHandler = new TestInvocationHandler(new SayImpl()); Say say = (Say)Proxy.newProxyInstance(SayImpl.class.getClassLoader(), SayImpl.class.getInterfaces(), testInvocationHandler ); say.sayHello("my dear"); }
执行结果:接口
invoke begin
method :sayHello is invoked!
hello:my dear
invoke endget