【发布时间】:2013-02-03 08:35:06
【问题描述】:
在 Java 中是否可以从实际字段中获取字符串中的字段名称?喜欢:
public class mod {
@ItemID
public static ItemLinkTool linkTool;
public void xxx{
String fieldsName = *getFieldsName(linkTool)*;
}
}
PS:我不是在寻找字段的类/类名或从 String 中的名称获取 Field。
编辑:
当我查看它时,我可能不需要获取字段名称的方法,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 中是不可能的,但谁知道......)
【问题讨论】:
-
如果字段不是私有的,那么可以从代码的特定部分知道被引用的字段的名称,但分析字节码。您可以为此使用 ASM 库。
-
字段名称是什么意思?你的例子中是那个字符串“linkTool”吗?
-
您是指您自己编写的类的字段名称还是其他类的名称?
-
请注意,
ItemLinkTool可能不止一种方法。在这种情况下,您的getFieldsName方法应该返回什么? -
我不确定我是否写得很清楚,我想要与以下相同的功能: this.getClass().getField("linkTool") 只是没有字符串部分 ~ this.getClass() .getField(linkTool).
标签: java reflection field