先定義一個接口HouseInter
package com.cn;
public interface HouseInter {
public void rentHouse();
public void cancelHouse();
}
定義一個實現上面接口的類HouseOwner
package com.cn;
public class HouseOwner implements HouseInter {
public void rentHouse() {
System.out.println("租房");
}
public void cancelHouse() {
System.out.println("退房");
}
}
再寫一個實現InvocationHandler的類ProxyHouse
package com.cn;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class ProxyHouse implements InvocationHandler{
private Object target;
public ProxyHouse(Object target)
{
this.target = target;
}
public Object invoke(Object arg0, Method method, Object[] arg2)
throws Throwable {
//接口類的方法執行之前
System.out.println("驗證用戶信息");
//接口類的方法執行
Object result = method.invoke(target, arg2);
//接口類的方法執行之後
System.out.println("結束");
return result;
}
}
最後寫一個測試類TestProxy
package com.test;
import java.lang.reflect.Proxy;
import com.cn.HouseInter;
import com.cn.HouseOwner;
import com.cn.ProxyHouse;
public class TestProxy {
public static void main(String[] args) {
HouseInter houseInter = new HouseOwner();
ProxyHouse proxy = new ProxyHouse(houseInter);
//創建代理對象
//這裏的參數不用HouseInter.class.getClassLoader()否則會出現類轉換異常
HouseInter hi = (HouseInter)Proxy.newProxyInstance(houseInter.getClass().getClassLoader(), houseInter.getClass().getInterfaces(), proxy);
hi.rentHouse();
}
}
測試結果
驗證用戶信息
退房
結束