java动态代理demo

首先一个接口

public interface MyInterface {


    void method1(String arg);
}

再写一个接口实现类

public class MyInterfaceImpl implements MyInterface {


    /*
     * (non-Javadoc)
     * @see reflectStudy.MyInterface#method1()
     */
    @Override
    public void method1(String arg) {
        System.out.println("MyInterfaceImpl:arg=" + arg);


    }


}

然后就是代理类,

动态代理: 如果想要完成动态代理,首先需要定义一个InvocationHandler接口的子类,已完成代理的具体操作。

public class MyInvocationHandler implements InvocationHandler {


    private Object obj = null;


    public Object getNewInstance(Object obj) {
        this.obj = obj;
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this);
    }


    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {


        return method.invoke(this.obj, args);
    }


}

client测试

/**
     * 
     * 
     * @throws Throwable
     * @throws SecurityException
     */
    private static void invocationHandler2() throws SecurityException, Throwable {
        MyInvocationHandler demo = new MyInvocationHandler();
        MyInterface impl = (MyInterface) demo.getNewInstance(new MyInterfaceImpl());
        String arg = "hello";
        Object[] objs = new Object[] { arg };
        demo.invoke(impl, MyInterface.class.getMethods()[0], objs);
        impl.method1("helllo");
 
    }

run result:

       MyInterfaceImpl:arg=hello
       MyInterfaceImpl:arg=helllo


猜你喜欢

转载自blog.51cto.com/10983206/2564136