JAVA代理

java.lang.reflect.Proxy
只能过有接口的类进行代理
建立代代理类的handler ,实现invocationHandler的invoke接口
如:

public class TestHandler implements InvocationHandler
{
    Object target;
   
    public TestHandler(Object obj)
    {
        // TODO Auto-generated constructor stub
        this.target = obj;
    }
   
    public Object invoke(Object arg0, Method arg1, Object[] arg2)
        throws Throwable
    {
        // TODO Auto-generated method stub
        Object result = arg1.invoke(target, arg2);
        if("test".equals(result))
        {
            result = "fuck";
        }
        return result;
    }
   
}

获取代理类:
Test test = new TestImpl("test");
       
        InvocationHandler handler = new TestHandler(test);
       
        Test proxy = (Test)Proxy.newProxyInstance(test.getClass().getClassLoader(),
            test.getClass().getInterfaces(), handler);
       
        System.out.println(proxy.print());

你可能感兴趣的:(java代理)