Java Casting Interface to Class

后端 未结 8 1314
闹比i
闹比i 2020-12-05 08:03
public class InterfaceCasting {

    private static class A{}

    public static void main(String[] args) {
        A a = new A();
        Serializable serializable          


        
8条回答
  •  粉色の甜心
    2020-12-05 08:41

    While I don't know the correct answer, it's usually not a good idea to cast an interface to a class, for several reasons.

    a) An interface defines a contract, it guarantees behavior. A class may define more than this contract, usage of the other methods may have unexpected side-effects and break APIs. E.g. when a method is passed a list and you find out the passed object is actually a LinkedList and you cast it and use the Queue based methods it also defines, you are breaking the API.

    b) also, the object with the interface may not be a "real" object at runtime, but perhaps a service proxy created around the original object by a library such as Spring or EJB. Your cast will fail in those cases.

    If you absolutely must cast, never do it without an instanceof check:

    if(myServiceObject instanceof MyServiceObjectImpl){
        MyServiceObjectImpl impl = (MyServiceObjectImpl) myServiceObject;
    }
    

提交回复
热议问题