Downcast IFile to File

时间:2018-01-26 08:06:18

标签: java eclipse eclipse-plugin

将IFile转发到文件是否安全?

File downCastedFile = (File) getSomeIFile();

或者我应该从here选择其中一种解决方案?

1 个答案:

答案 0 :(得分:1)

规则是,如果将接口类型的引用强制转换为任何其他类型,编译器将盲目地信任您。

在运行时期间,如果引用指向您正在将其转换为所有类型的对象的引用将顺利进行,否则将引发ClassCastException

例如,假设你有:

class FoodProcessor implements CoffeeExpress, Blender, Juicer{....}

然后:

Object o = new FoodProcessor();
CoffeeExpress c = (CoffeeExpress)o;//fine
Blender b = (Blender)o;//fine
Juicer j = (Juicer)o;//fine
FoodProcessor f = (FoodProcessor)o;//fine
A a = new A();//where A does not implement any of CoffeeExpress, Blender and Juicer and does not derive from FoodProcessor
c = (CoffeeExpress)a;//ClassCastException
b = (Blender)a;//ClassCastException
j = (Juicer)a;//ClassCastException
f = (FoodProcessor)a;//ClassCastException

要回答您的问题,您必须问自己:getSomeIFile();是否返回File类型的值或源自File的值?