IStreamContentAccessor

IStreamContentAccessor

我正在研究一些专业编写的代码,并遇到了这个片段。 (我希望这个片段足以回答我的问题-如果不能让我知道)

...yada yada yada ....

private ITypedElement format(final ITypedElement elementToFormat) {
        try {
            if (elementToFormat instanceof IStreamContentAccessor) {
                final IStreamContentAccessor resNode = (IStreamContentAccessor) elementToFormat;
                final InputStream contentIs = resNode.getContents();
                final String contentsString = fromInputStreamToString(contentIs);
                final Map options = JavaCore.getOptions();
.... etc....

仅当ifelementToFormat的实例时,才会运行IStreamContentAccessor段。为什么程序随后在if语句“final IStreamContentAccessor resNode = (IStreamContentAccessor)elementToFormat;"”之后做出第一个语句?

将某事物强制转换为它必须已经具有的类型可能是什么意思?

最佳答案

程序员可能知道这是IStreamContentAccessor,但没有强制转换,编译器就不知道这是IStreamContentAccessor,因此它不会让程序员访问IStreamContentAccessor类的任何特定字段/方法。

class ClassA {
    Object field1;
}

class ClassB extends ClassA
    Object field2;
}

ClassA obj = new ClassB();
obj.field1;  // This is fine, the compiler knows it's a ClassA
obj.field2;  // This isn't allowed - as far as the compiler knows it's a ClassA, not a ClassB
((ClassB)obj).field2;  // This is allowed - now the compiler knows it's a ClassB

10-08 16:40