I have a below class and i need to get field name from getter method using java reflection. Is it possible to get field name or property name using getter method?
class A {
private String name;
private String salary;
// getter and setter methods
}
My questions is: can i get field/property name by getter method? If I use getName(), can I get name property? I need name property but not its value. Is it possible through java reflection?
The POJO class must be public. It must have a public default constructor. It may have the arguments constructor. All objects must have some public Getters and Setters to access the object values by other Java Programs.
The getter method returns the value of the attribute. The setter method takes a parameter and assigns it to the attribute. Once the getter and setter have been defined, we use it in our main: public static void main(String[] args) { Vehicle v1 = new Vehicle(); v1. setColor("Red"); System.
Getter returns the value (accessors), it returns the value of data type int, String, double, float, etc. For the program's convenience, getter starts with the word “get” followed by the variable name. While Setter sets or updates the value (mutators). It sets the value for any variable used in a class's programs.
We can invoke setters and getters of a POJO class by using its variable name by using Reflection API of java. Reflection API is used to examine the behavior of classes, interfaces, methods at runtime.
yes it's 100% possible..
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;
}
The reflection-util library provides a way to determine the property (name) in a type-safe manner. For example by using the getter method:
String propertyName = PropertyUtils.getPropertyName(A.class, A::getSalary);
The value of propertyName
would be "salary"
in this case.
Disclaimer: I’m one of the authors of the reflection-util library.
You cannot inspect what code does by using reflection.
You can assume that a getName()
method read a field called name
and does nothing else. However there is no requirement for it to so. e.g. the field name might be m_name
or _name
or nameField
or not even be a field.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With