Is there a standard library (such as org.apache.commons.beanutils or java.beans) that will take a string field name and convert it to the standard method name? I'm looking all over and can't find a simple string conversion utility.
The JavaBean introspector is possibly the best choice. It handles "is" getters for boolean types and "getters" which take an argument and setters with none or two arguments and other edge cases. It is nice for getting a list of JavaBean fields for a class.
Here is an example,
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
public class SimpleBean
{
private final String name = "SimpleBean";
private int size;
public String getName()
{
return this.name;
}
public int getSize()
{
return this.size;
}
public void setSize( int size )
{
this.size = size;
}
public static void main( String[] args )
throws IntrospectionException
{
BeanInfo info = Introspector.getBeanInfo( SimpleBean.class );
for ( PropertyDescriptor pd : info.getPropertyDescriptors() )
System.out.println( pd.getName() );
}
}
This prints
class
name
size
class
comes from getClass()
inherited from Object
EDIT: to get the getter or setter and its name.
public static String findGetterName(Class clazz, String name) throws IntrospectionException, NoSuchFieldException, NoSuchMethodException {
Method getter = findGetter(clazz, name);
if (getter == null) throw new NoSuchMethodException(clazz+" has no "+name+" getter");
return getter.getName();
}
public static Method findGetter(Class clazz, String name) throws IntrospectionException, NoSuchFieldException {
BeanInfo info = Introspector.getBeanInfo(clazz);
for ( PropertyDescriptor pd : info.getPropertyDescriptors() )
if (name.equals(pd.getName())) return pd.getReadMethod();
throw new NoSuchFieldException(clazz+" has no field "+name);
}
public static String findSetterName(Class clazz, String name) throws IntrospectionException, NoSuchFieldException, NoSuchMethodException {
Method setter = findSetter(clazz, name);
if (setter == null) throw new NoSuchMethodException(clazz+" has no "+name+" setter");
return setter.getName();
}
public static Method findSetter(Class clazz, String name) throws IntrospectionException, NoSuchFieldException {
BeanInfo info = Introspector.getBeanInfo(clazz);
for ( PropertyDescriptor pd : info.getPropertyDescriptors() )
if (name.equals(pd.getName())) return pd.getWriteMethod();
throw new NoSuchFieldException(clazz+" has no field "+name);
}
A wild one-liner appeared!
String fieldToGetter(String name)
{
return "get" + name.substring(0, 1).toUpperCase() + name.substring(1);
}
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