在Java中是否能够从实际字段获取字段名称的字符串,例如:
public class mod {
@ItemID
public static ItemLinkTool linkTool;
public void xxx{
String fieldsName = *getFieldsName(linkTool)*;
}
}
PS:我不是在寻找一个字段的类/类名或从字符串中获取字段的名称。
编辑:
当我查看时,我可能不需要一个方法来获取字段的名称,Field实例(从字段的“代码名称”)就足够了。[例如:Field myField = getField(linkTool)
]
在Java本身中可能没有像我想要的东西。我会看一下ASM库,但最终可能会使用字符串作为字段的标识符 :/
编辑2: 我的英语不太好(但即使在我的母语中,我也会遇到解释这个问题的问题),所以我再添加一个例子。希望现在更清楚了:
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中不可能,但谁知道呢..)