public void SayHello();}public class HelloWorldImpl implements HelloWorld { public void SayHello() { System.out.println("hello"); }}public class HelloWorldMSSQL extends HelloWorldImpl {}这是接口、实现类、扩展类
这是测试HelloWorld hw = new HelloWorldImpl();没问题 如果是HelloWorld hw = new HelloWorldMSSQL();就报错java.lang.ClassCastException: $Proxy0 cannot be cast to test.invoke.HelloWorld try { // HelloWorld hw = new HelloWorldMSSQL(); HelloWorld hw = new HelloWorldImpl(); InvocationHandler handler = new HelloWorldHandler(hw);
所以可以用动态代理
public void SayHello();}public class HelloWorldImpl implements HelloWorld { public void SayHello() {
System.out.println("hello"); }}public class HelloWorldMSSQL extends HelloWorldImpl {}这是接口、实现类、扩展类
public HelloWorldHandler(Object obj) { this.objOriginal = obj ; }
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object result ; //方法调用之前 doBefore(); //调用原始对象的方法 result = method.invoke(this.objOriginal ,args); //方法调用之后 doAfter();
return result ; } private void doBefore() { System.out.println("before method invoke!"); } private void doAfter() { System.out.println("after method invoke!"); }}
如果是HelloWorld hw = new HelloWorldMSSQL();就报错java.lang.ClassCastException: $Proxy0 cannot be cast to test.invoke.HelloWorld
try
{
// HelloWorld hw = new HelloWorldMSSQL();
HelloWorld hw = new HelloWorldImpl();
InvocationHandler handler = new HelloWorldHandler(hw);
HelloWorld proxy = (HelloWorld) Proxy.newProxyInstance( hw.getClass().getClassLoader(), hw.getClass().getInterfaces(), handler);
proxy.SayHello();
}
catch(Exception e)
{
e.printStackTrace();
}
你去实现,出问题帖出来一起解决
hw.getClass().getInterfaces()改成hw.getClass().getSuperclass().getInterfaces()
HelloWorld proxy = (HelloWorld) Proxy.newProxyInstance(hw.getClass().getClassLoader(),
hw.getClass().getSuperclass().getInterfaces(), handler);
我试了,好用。