Java代理,转型异常,怎么解决 ?
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class Test implements InvocationHandler {
private A target ;
public A bind(A target)
{
this.target = target ;
return (A)Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces() ,
this ) ;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object obj = null ;
System.out.println(method.getName());
try{
obj = method.invoke(target , args) ;
}
catch( NullPointerException nullErr )
{
System.out.println("ok");
return null ;
}
return obj ;
}
public static void main(String[] args) {
A a = new Test().bind(new A()) ;
}
}
class A
{
int i = 9 ;
int j = 9 ;
}
问题:Java代理,转型异常,怎么解决 ?
求指教 !
------解决方案--------------------
jdk动态代理只能代理有接口的类, 代理接口方法
------解决方案--------------------
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class Test implements InvocationHandler {
private Test_1 target;
public Object bind(Test_1 target) {
this.target = target;
return Proxy.newProxyInstance(target.getClass().getClassLoader(),
target.getClass().getInterfaces(), this);
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object obj = null;
System.out.println(method.getName());
try {
obj = method.invoke(target, args);
} catch (NullPointerException nullErr) {
System.out.println("ok");
return null;
}
return obj;
}
public static void main(String[] args) {
Interface_Test a = (Interface_Test) new Test().bind(new Test_1());
a.test();
}
}
interface Interface_Test {
public void test();
}
class Test_1 implements Interface_Test {
int i = 9;
int j = 9;
public void test() {
System.out.println("执行Test");
}
}
给你改了一下。