像这样的铸造目的?

时间:2015-06-09 16:07:12

标签: java

这样投射有什么目的吗?

不好意思,看起来我的代码剥离引起了一些混乱。完整的方法是这样的:

public String foo() {
    Object obj = getAnObject(); //returns various objects that all extend Object
    A aVar = null;

    if(!(obj instanceof A)) { return null; }

    if(object != null)
        aVar = (A) object; //Cast in question since instanceof check is done

    Object obj1 = ((aVar != null) ? aVar : new A());
    sendToJSPasJSON(obj1);

    return null;
}

1 个答案:

答案 0 :(得分:2)

我能想到的唯一原因是检查obj是否为A类的对象(如果不是,则抛出ClassCastException)。 但这可以使用instanceof

完成
if (!(obj instanceof A)) {
    // do something (throw an exception)
}

除非在getAnObject返回无法转换为A的内容时抛出异常,否则您编写的代码可能会简化为:

Object obj = getAnObject();
Object obj1 = ((obj != null) ? obj : new B());

甚至

if (getAnObject() != null) {
    new B();
}

但是对于构造函数而言,这是一种非常糟糕的形式,因为副作用会产生副作用,如果对象不是new B(),这将是null的唯一原因。