java动态代理

来源:互联网 发布:海洋cms采集资源 编辑:程序博客网 时间:2024/06/05 07:56
package com.test;


import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;


/**
 * @author jack
 * 2015-2-10
 * 
 */


interface IHello{
public void sayHello();
}


class IHelloImpl implements IHello{
public void sayHello(){
System.out.println("Hello everyone!");
}
}


class MyInvocationHandler implements InvocationHandler{

private Object obj;

public Object bind(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 {
System.out.println("begin===");
Object temp=method.invoke(obj, args);
System.out.println("end===");
return temp;
}
}


public class ProxyTest{
public static void main(String[] args) {
IHello i=(IHello)new MyInvocationHandler().bind(new IHelloImpl());
i.sayHello();
}
}
0 0
原创粉丝点击