示例代码:
注意:
[list]
[*] Proxy 前的强制转换必须为接口,否则会出现[quote]java.lang.ClassCastException: $Proxy0 cannot be cast to [/quote]some Object。
[*] TestInterface 为要代理的接口类型。
[*] TestProxy 为实现了 TestInterface 的接口。
[*] 方法的第二个参数 new Class[]{TestInterface.class},也经常看到写成 TestProxy.class.getInterfaces()。
[/list]
TestInterface s = (TestInterface)Proxy.newProxyInstance(TestProxy.class.getClassLoader(), new Class[]{TestInterface.class}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
if(method.getName().equals("toString")){
return "This is a String proxy.";
}
return null;
}
});
System.out.println(s);
注意:
[list]
[*] Proxy 前的强制转换必须为接口,否则会出现[quote]java.lang.ClassCastException: $Proxy0 cannot be cast to [/quote]some Object。
[*] TestInterface 为要代理的接口类型。
[*] TestProxy 为实现了 TestInterface 的接口。
[*] 方法的第二个参数 new Class[]{TestInterface.class},也经常看到写成 TestProxy.class.getInterfaces()。
[/list]