JDK动态代理实例

public interface Hello { public void hello(); }

 

import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import org.Hello; public class SayHello implements Hello{ @Override public void hello() { // TODO Auto-generated method stub System.out.println("hello"); } static class MyInvocationHandler implements InvocationHandler{ private Object target; public MyInvocationHandler(Object target){ this.target=target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // TODO Auto-generated method stub System.out.println(method.getName()+"-------start"); Object result=method.invoke(target, args); System.out.println(method.getName()+"--------end"); return result; } } static class ProxyFactory{ InvocationHandler h; Class cls; public ProxyFactory(String className,InvocationHandler h) throws ClassNotFoundException{ cls=Class.forName(className); this.h=h; } public Object create(){ return Proxy.newProxyInstance(cls.getClassLoader(), cls.getInterfaces(), h); } } public static void main(String[] args) throws ClassNotFoundException { Hello s=new SayHello(); InvocationHandler h=new MyInvocationHandler(s); ProxyFactory proxyFactory=new ProxyFactory(SayHello.class.getName(), h); Hello sf=(Hello) proxyFactory.create(); sf.hello(); } } -----------------会输出 hello-------start hello--------end

 

大家可以debug,看看代码怎么走的。

下次研究过后会给出更详细的说明,^_^ 要睡觉了

你可能感兴趣的:(jdk,object,String,Class,import,interface)