Javaで実際のフィールドから文字列でフィールドの名前を取得することは可能ですか?お気に入り:
public class mod {
@ItemID
public static ItemLinkTool linkTool;
public void xxx{
String fieldsName = *getFieldsName(linkTool)*;
}
}
PS:フィールドのクラス/クラス名を探したり、文字列の名前からフィールドを取得したりしていません。
編集:私がそれを見ているとき、私はおそらくフィールドの名前を取得するためのメソッドを必要としないでしょう、フィールドインスタンス(フィールドの「コードネーム」から)で十分でしょう。[例Field myField = getField(linkTool)
]
おそらく、Java自体に私が望むようなものはないでしょう。ASMライブラリを見ていきますが、最終的には文字列をフィールドの識別子として使用することになります:/
EDIT2:私の英語は上手ではありません(しかし、私の母国語でもこれを説明するのに問題があります)ので、もう1つの例を追加します。うまくいけば、それは今より明確になるでしょう:
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では不可能だと思いますが、誰が知っていますか..)