使用pojo/java bean的getter方法获取属性/字段名称?

use*_*403 14 java reflection

我有一个下面的类,我需要使用java反射从getter方法获取字段名称.是否可以使用getter方法获取字段名称或属性名称?

class A {

    private String name;
    private String salary;

    // getter and setter methods
}
Run Code Online (Sandbox Code Playgroud)

我的问题是:我可以通过getter方法获得字段/属性名称吗?如果我使用getName(),我可以得到name属性吗?我需要name属性,但不需要它的值.是否可以通过java反射?

Vis*_*kia 15

是的,这是100%的可能..

public static String getFieldName(Method method)
{
    try
    {
        Class<?> clazz=method.getDeclaringClass();
        BeanInfo info = Introspector.getBeanInfo(clazz);  
        PropertyDescriptor[] props = info.getPropertyDescriptors();  
        for (PropertyDescriptor pd : props) 
        {  
            if(method.equals(pd.getWriteMethod()) || method.equals(pd.getReadMethod()))
            {
                System.out.println(pd.getDisplayName());
                return pd.getName();
            }
        }
    }
    catch (IntrospectionException e) 
    {
        e.printStackTrace();
    }
    catch (Exception e) 
    {
        e.printStackTrace();
    }


    return null;
}
Run Code Online (Sandbox Code Playgroud)

  • 如何发送方法作为参数?getFieldName(cls.getProperty())将提供价值 (2认同)

mic*_*czy 8

您可以使用lombok 的 @FieldNameConstants注释。

注释你的类:

import lombok.experimental.FieldNameConstants;
import lombok.AccessLevel;

@FieldNameConstants
public class FieldNameConstantsExample {
  private final String name;
  private final int rank;
}
Run Code Online (Sandbox Code Playgroud)

它在后台生成以下代码:

public class FieldNameConstantsExample {
  private final String name;
  private final int rank;
  
  public static final class Fields {
    public static final String name = "name";
    public static final String rank = "rank";
  }
}
Run Code Online (Sandbox Code Playgroud)

因此,您可以通过以下方式访问属性名称:

FieldNameConstantsExample.Fields.name
Run Code Online (Sandbox Code Playgroud)

这是字符串"name"


Jas*_*son 7

仅删除"get"或"is"前缀和小写第一个字母并不完全合适.例如,getID的相应bean名称将是ID而不是iD.

获取bean名称的最简单方法是删除get或is前缀,然后将结果传递给Introspector.decapitalize.

这是我写的一个方法来做这件事:

private String getBeanName(String methodName)
{
    // Assume the method starts with either get or is.
    return Introspector.decapitalize(methodName.substring(methodName.startsWith("is") ? 2 : 3));
}
Run Code Online (Sandbox Code Playgroud)

  • @NamelessVoice,你是正确的,变量应该以小写字母开头.但是,我们不是在谈论变量.我们谈论的是房产.请参阅Javabean标准的第8.8节:http://download.oracle.com/otn-pub/jcp/7224-javabeans-1.01-fr-spec-oth-JSpec/beans.101.pdf (2认同)

vel*_*s4j 6

你可以

Field[] declaredFields = A.class.getDeclaredFields();
        for(Field f:declaredFields){
            System.out.println(f.getName());
        }
Run Code Online (Sandbox Code Playgroud)


Pet*_*rey 5

您无法使用反射检查代码的作用.

您可以假设一个getName()方法读取一个被调用的字段name,而不执行任何其他操作 但是没有必要这样做.例如,字段名可能是m_name或者_name或者nameField甚至不是一个领域.


Ben*_*gel 5

反射util的库提供一种方法来确定在一个类型安全的方式的属性(名称)。例如,使用getter方法:

String propertyName = PropertyUtils.getPropertyName(A.class, A::getSalary);
Run Code Online (Sandbox Code Playgroud)

的值propertyName"salary"在这种情况下。

免责声明:我是Reflection-util库的作者之一。


Ara*_*ram 1

如果您的 bean 遵循 JavaBean 约定,那么您可以使用反射来获取所有“get”和“is”方法,并从检索到的方法名称中删除“get”或“is”前缀,这样您就获得了字段名称。

更新

// Get the Class object associated with this class.
    MyClass myClass= new MyClass ();
    Class objClass= myClass.getClass();

    // Get the public methods associated with this class.
    Method[] methods = objClass.getMethods();
    for (Method method:methods)
    {
        String name=method.getName();
        if(name.startsWith("get") || name.startsWith("is"))
        {
           //...code to remove the prefixes
        }
    }
Run Code Online (Sandbox Code Playgroud)