为什么要使用ClassCastException?

时间:2018-09-09 10:15:16

标签: java exception

package com.lean.ssm.chapter2.proxy1;

public interface HelloWorld {

    void sayHelloWorld();

}
package com.lean.ssm.chapter2.proxy1;

public class HelloWorldImp {
    public void sayHelloWorld() {
        System.out.println("hello");
    }

}
package com.lean.ssm.chapter2.proxy1;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JdkProxyExample implements InvocationHandler {

    private Object target = null; 

    public Object bind(Object target) {  
        this.target = target;
        return
                Proxy.newProxyInstance(target.getClass().getClassLoader(),
                        target.getClass().getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("进入代理逻辑方法");
        System.out.println("调度真实对象之前的服务");
        Object obj = method.invoke(target, args);
        System.out.println("调度真实对象之后的服务");
        return obj;
    }
}
package com.lean.ssm.chapter2.proxy1;

public class ProxyTest {
     public static void main(String[] args) {
            testJdkProxy();}
        private static void testJdkProxy() {
            JdkProxyExample jdk = new JdkProxyExample();
            HelloWorld proxy = (HelloWorld) jdk.bind(new HelloWorldImp());
            proxy.sayHelloWorld();}

}

控制台: 线程“主”中的异常java.lang.ClassCastException:com.sun.proxy。$ Proxy0无法转换为com.lean.ssm.chapter2.proxy1.HelloWorld     在com.lean.ssm.chapter2.proxy1.ProxyTest.testJdkProxy(ProxyTest.java:8)     在com.lean.ssm.chapter2.proxy1.ProxyTest.main(ProxyTest.java:5)

2 个答案:

答案 0 :(得分:0)

ClassCastException在实现HelloWorldImp实施HelloWorld时消失:

class HelloWorldImp implements HelloWorld {
    @Override
    public void sayHelloWorld() {
        System.out.println("hello");
    }
}

问题出在bind(Object)方法中。

根据Proxy.newProxyInstance(ClassLoader, Class[], InocationHandler) docs。第二个参数是

  

代理类要实现的接口列表

由于HelloWorldImp尚未实现任何内容,因此target.getClass().getInterfaces()调用返回了空数组,并且生成的代理未实现HelloWorld接口。因此,

HelloWorld proxy = (HelloWorld) jdk.bind(new HelloWorldImp()); 

失败

答案 1 :(得分:-1)

如果您将类A的对象转换为类B的对象,并且它们不是兼容类型,则将引发强制转换例外情况。 例如。

Object obj = Integer.valueOf(100);
String value = (String)obj;  // ClassCastException occurs.