用Proxy 的静态方法 newProxyInstance 创建代理

示例代码:
		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);

注意:
  • Proxy 前的强制转换必须为接口,否则会出现
    引用
    java.lang.ClassCastException:  $Proxy0 cannot be cast to
    some Object。
  • TestInterface 为要代理的接口类型。
  • TestProxy 为实现了 TestInterface 的接口。
  • 方法的第二个参数 new Class[]{TestInterface.class},也经常看到写成 TestProxy.class.getInterfaces()。

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