Is it possible in Java to get a name of field in string from the actual field? like:
public class mod {
@ItemID
public static ItemLinkTool linkTool;
public void xxx{
String fieldsName = *getFieldsName(linkTool)*;
}
}
PS: I'm not looking for a field's class/class name or getting Field from name in String.
EDIT:
When I'm looking at it I probably wouldn't need a method to get a field's name, the Field instance (from field's "code name") would suffice. [e.g. Field myField = getField(linkTool)
]
There probably isn't anything like I want in Java itself. I'll take a look at the ASM library, but in the end I might end up using the string as an identifier for fields :/
EDIT2: My english isn't great (but even in my native language I'd have problems explaining this), so I'm adding one more example. Hopefuly it will be more clear now:
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));
}
}
}
The question is: how could look the constructItemIdeal method? (From answers and googling around I thing it's not possible in Java, but who knows..)
See Question&Answers more detail:os