小编Zer*_*rak的帖子

在instanceof方法中使用Class<?>参数

我有以下方法可以返回不同类型的可存储(例如:食物,矿石)。

库存.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)

java casting instanceof java-15

2
推荐指数
1
解决办法
470
查看次数

标签 统计

casting ×1

instanceof ×1

java ×1

java-15 ×1