0

我可以使用反射在 Java 中使用方法获取字段(变量/属性)名称吗?我在下面的代码中解释我的场景。

例如,我有一节课

class MyBean
{
    String name;
    String Name;

    public String getName() {
        return Name;
    }
    public void setName(String name) {
        this.Name = name;
    }
}

现在我想通过使用 java.lang.reflect.Method "getName()" 来输入字段 "Name" ...我能得到它吗?

我想要这样的功能..

public String getFieldName(Method method)
{
    String fieldName=null;

    // code for finding field/variable/property name using method

    return fieldName;
}

请帮助我,如果可能的话......提前谢谢

4

3 回答 3

0

This works, but your class is not cleanly defined.
Fields should be named using camelCase notation starting with a lower char:

class Info
{
    public String name1;
    private String name2;
}

Now you have an object info:

Info info;

Then you want to get the value of name1:

Here is a full Test case showing all:

public class InfoTest extends TestCase{

public static class Info {

    private    String name1;
    public     String name2;
    protected  String name3;
    String name4;

    /**
     * Default constructor.
     */
    public Info() {
        name1 = "name1Value";
        name2 = "name2Value";
        name3 = "name3Value";
        name4 = "name4Value";
    }

}

public void testReflection() throws IllegalArgumentException, IllegalAccessException {

    Info info1 = new Info();

    Field[] infoFields = info1.getClass().getDeclaredFields();
    for (int i = 0; i < infoFields.length; i++) {
        Field fieldName = infoFields[i];
        System.out.println("the name of the field " + i +  ":" + fieldName.getName());
        fieldName.setAccessible(true);
        Object info1ValObj = infoFields[0].get(info1);
        System.out.println("the value of the field: " + info1ValObj.toString());
    }
}

}

The output then is:
the name of the field 0:name1
the value of the field: name1Value
the name of the field 1:name2
the value of the field: name1Value
the name of the field 2:name3
the value of the field: name1Value
the name of the field 3:name4
the value of the field: name1Value

于 2012-11-22T14:55:35.840 回答
0

如果你按照 JavaBeans 约定命名你的字段,这应该做所有的事情:

public String getFieldName(Method method) {
    return method.getName().substring(3).toLowerCase();
}

所以 getName() 或 setName() 应该返回“name”

于 2012-11-22T14:49:58.300 回答
-1

你的意思是?

public String getFieldName(Method method) {
    return method.getName().substring(3);
}

camcelCase顺便说一句:字段名称不应该是TitleCase

于 2012-11-22T14:35:08.957 回答