1 回答

TA貢獻1874條經驗 獲得超12個贊
您可以使用類強制轉換:
public static void main(String args[]) {
Object1Type a = new Object3Type();
if (a instanceof Object3Type) {
Object3Type b = (Object3Type) a;
byte[] bytes = b.value;
}
}
但這是危險的,不推薦的做法。演員正確性的責任在于程序員。請參閱示例:
class Object3Type implements Object2Type {
byte[] value;
}
class Object4Type implements Object2Type {
byte[] value;
}
class DemoApplication {
public static void main(String args[]) {
Object1Type a = new Object3Type();
Object3Type b = (Object3Type) a; // Compiles and works without exceptions
Object4Type c = (Object4Type) a; // java.lang.ClassCastException: Object3Type cannot be cast to Object4Type
}
}
如果這樣做,請至少使用前面的 instanceof 運算符檢查對象。
我建議您在其中一個接口(現有或新)中聲明一些 getter,并在類中實現此方法:
interface Object1Type extends Base {
byte[] getValue();
}
interface Object2Type extends Object1Type {}
class Object3Type implements Object2Type {
byte[] value;
public byte[] getValue() {
return value;
}
}
class DemoApplication {
public static void main(String args[]) {
Object1Type a = new Object3Type();
byte[] bytes = a.getValue();
}
}
添加回答
舉報