使用类<?>实例法中的参数
我有以下方法可以返回不同类型的存储(例如:食物,矿石)。
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使您的方法通用:
请注意
cls.cast
的使用。这就像(S)存储
,但没有编译器警告。Make your method generic:
Note the use of
cls.cast
. That's like(S) storable
but without the compiler warning.