java 取字段_java – 获取字段的名称

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中是不可能的,但谁知道..)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值