[英]change type of Object depending on method argument
So once again, sorry this questian might be answered/asked a lot allready, but I'm not really sure what i am searching for 因此,再次抱歉,这个询问者已经准备好了很多,但我不确定我要寻找的是什么
I'm currently making a mod for a game and need to register custom items i created. 我目前正在为游戏制作模组,需要注册我创建的自定义物品。 I created custom classes for every type of item which contain various variables I need to access.
我为每种类型的项目创建了自定义类,其中包含需要访问的各种变量。 The problem is, the class(es) they all inherit from does not have these variables/data.
问题是,它们都从中继承的类没有这些变量/数据。
My initial attempt was something like this (pseudo code'ish) 我最初的尝试是这样的(伪代码“ ish”)
public void addItem(Item itemc)
{
Object item = null;
if (itemc.getClass().equals(ItemTool))
item = (ItemTool) itemc;
if (itemc.getClass().equals(ItemFood))
item = (ItemFood) itemc;
.......etc..........
registerItem(item,item.name);
registerItemRenderer(item,item.meta,item.model);
}
But that doesn't work and i get an error saying item (treated as an Object as initialized) does not have these members. 但这不起作用,并且我收到一条错误消息,指出项目(作为初始化的对象处理)没有这些成员。
Right now i just overloaded the method addItem to accept every custom item class i made (over 10 atm), but thats not really what i want. 现在,我只是重载了addItem方法来接受我制作的每个自定义项目类(超过10个atm),但这并不是我真正想要的。
Is there a way to change the type of an Object to whatever class i will pass as argument and then work with it? 有没有一种方法可以将Object的类型更改为我将作为参数传递然后使用的任何类?
You could move the extraction of item.name
into the if
: 您可以将
item.name
的提取内容item.name
if
:
Object item = null;
Object itemName = null;
if (itemc.getClass().equals(ItemTool)) {
item = (ItemTool) itemc;
itemName = item.name;
} else {
if (itemc.getClass().equals(ItemFood)) {
item = (ItemFood) itemc;
itemName = item.name;
}
}
registerItem(item, itemName);
but it would be far more OO-like to create an Interface
for Item
to include a getName
-method which every Item
implements and your method does not have to know which type your item is to obtain the name: 但是为
Item
创建一个包含getName
方法的Item
Interface
更像面向对象,每个Item
实现一个getName
方法,并且您的方法不必知道您的项目将使用哪种类型来获取名称:
public void addItem(Item item) {
registerItem(item, item.getName());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.