Zer*_*rak 2 java casting instanceof java-15
我有以下方法可以返回不同类型的可存储(例如:食物,矿石)。
库存.java
public Storable get(Class<? extends Storable> cls) {
for (Storable storable : inventory) {
if(cls.isInstance(storable)) {
this.inventory.remove(storable);
return storable;
}
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
它有效,但是我被迫将结果投射如下:
Food food = (Food) inventory.get(Food.class);
Run Code Online (Sandbox Code Playgroud)
instanceof对于 Java 15 及更高版本,我们可以直接使用(链接到 javadoc )定义强制转换对象。我想知道是否可以使用这个新语法并直接返回强制转换的对象。
我尝试了这个,但instanceof关键字仅适用于类型而不是变量:
public Storable get(Class<? extends Storable> cls) {
for (Storable storable : inventory) {
if(storable instanceof cls castedItem) { //cls cannot be resolved to a type
this.inventory.remove(storable);
return castedItem;
}
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
使你的方法通用:
public <S extends Storable> S get(Class<S> cls) {
for (Storable storable : inventory) {
if (cls.isInstance(storable)) {
this.inventory.remove(storable);
return cls.cast(storable);
}
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
注意使用cls.cast. 这就像(S) storable但没有编译器警告。
| 归档时间: |
|
| 查看次数: |
470 次 |
| 最近记录: |