實現:
新建ITestDemo接口
package com.study.javastu3;
public interface ITestDemo {
public void test();
public void test1();
}
用ProxyDemo類實現ITestDemo接口
package com.study.javastu3;
public class TestDemoImpl implements ITestDemo{
@Override
public void test() {
System.out.println("執行test 0");
}
@Override
public void test1() {
System.out.println("執行test 1");
}
}
實現InvocationHandler的代理類 ProxyDemo
package com.study.javastu3;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/*
動態代理類
*/
public class ProxyDemo implements InvocationHandler {
Object obj;//被代理的對象
public ProxyDemo(Object obj){
this.obj = obj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println(method.getName()+" 方法開始執行!");
Object obj = method.invoke(this.obj,args); //執行代理對象的指定方法
System.out.println(method.getName()+" 方法結束執行!");
return obj;
}
}
測試:
package com.study.javastu3;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
public class Test2 {
public static void main(String[] args)
{
/**
* 如果一個對象想要通過Proxy.newProxyInstance()方法被代理,
* 那麼這個類中的類必須要有接口
* 就像本類的TestDemoImpl有ITestDemo接口
*/
ITestDemo test = new TestDemoImpl();
test.test();
test.test1();
// 需求,在執行test1和test2方法時,需要在執行之前打印test1或者test2開始執行,
// 在執行方法後,打印test1或者test2方法結束,打印的方法名要和當時調用的方法名一致
InvocationHandler handler = new ProxyDemo(test);
// Proxy.newProxyInstance(,,)
// 有三個參數,參數1是代理對象的類加載器,參數2是被代理對象的接口,參數3是代理對象
//返回的值就是成功代理後返回的對象,返回的值是Object類型,需要根據情況進行強轉
ITestDemo t = (ITestDemo) Proxy.newProxyInstance(handler.getClass().getClassLoader(),test.getClass().getInterfaces(),handler);
t.test();
t.test1();
}
}
/* 測試結果
執行test 0
執行test 1
test 方法開始執行!
執行test 0
test 方法結束執行!
test1 方法開始執行!
執行test 1
test1 方法結束執行!
*/