在
Java中可以从实际字段获取字符串中的字段名称吗?喜欢:
public class mod {
@ItemID
public static ItemLinkTool linkTool;
public void xxx{
String fieldsName = *getFieldsName(linkTool)*;
}
}
PS:我不是寻找一个字段的类/类名称或从String中的名称获取字段.
编辑:
当我看着它,我可能不需要一个方法来获取字段的名称,Field实例(从字段的“代码名称”)就足够了. [例如. Field myField = getField(linkTool)]
Java本身可能没有什么像我想要的.我将看看ASM库,但最终我可能会使用字符串作为字段的标识符:/
EDIT2:
我的英语不是很好(但即使是我的母语,我也会解释这个问题),所以我再增加一个例子.希望现在会更加清楚:
public class mod2 {
@ItemID
public static ItemLinkTool linkTool;
@ItemID
public static ItemLinkTool linkTool2;
@ItemID
public static ItemPipeWrench pipeWrench;
public void constructItems() {
// most trivial way
linkTool = new ItemLinkTool(getId("linkTool"));
linkTool2 = new ItemLinkTool(getId("linkTool2"));
pipeWrench = new ItemPipeWrench(getId("pipeWrench"));
// or when constructItem would directly write into field just
constructItem("linkTool");
constructItem("linkTool2");
constructItem("pipeWrench");
// but I'd like to be able to have it like this
constructItemIdeal(linkTool);
constructItemIdeal(linkTool2);
constructItemIdeal(pipeWrench);
}
// not tested, just example of how I see it
private void constructItem(String name){
Field f = getClass().getField(name);
int id = getId(name);
// this could be rewritten if constructors take same parameters
// to create a new instance using reflection
if (f.getDeclaringClass() == ItemLinkTool){
f.set(null, new ItemLinkTool(id));
}else{
f.set(null, new ItemPipeWrench(id));
}
}
}
问题是:怎么看看constructItemIdeal方法? (从我的答案和谷歌搜索在Java中是不可能的,但谁知道..)