使用类<?>实例法中的参数

发布于 2025-02-05 01:57:41 字数 1082 浏览 4 评论 0原文

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

intickory.java

public Storable get(Class<? extends Storable> cls) {
    for (Storable storable : inventory) {
        if(cls.isInstance(storable)) {
            this.inventory.remove(storable);
            return storable;
        }
    }
    return null;
}

它有效,但是我被迫施放以下结果:

Food food = (Food) inventory.get(Food.class);

使用java 15及以上,我们可以用instanceof 直接定义铸造的对象(链接到Javadoc )。我想知道我是否可以使用此新语法并直接返回铸造的对象。

我尝试了此操作,但是实例关键字仅适用于类型不变:

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;
}

I have the following method that can return different types of Storable (ex: Food, Ore).

Inventory.java

public Storable get(Class<? extends Storable> cls) {
    for (Storable storable : inventory) {
        if(cls.isInstance(storable)) {
            this.inventory.remove(storable);
            return storable;
        }
    }
    return null;
}

It works, however I'm forced to cast my result like below:

Food food = (Food) inventory.get(Food.class);

With Java 15 and above, we can define casted object directly with instanceof (link to javadoc). I'm wondering if I can use this new syntax and return casted object directly.

I tried this but instanceof keyword only works with type not variable:

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;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

全部不再 2025-02-12 01:57:42

使您的方法通用:

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;
}

请注意cls.cast的使用。这就像(S)存储,但没有编译器警告。

Make your method generic:

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;
}

Note the use of cls.cast. That's like (S) storable but without the compiler warning.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文