Существует ли стандартная библиотека (например, org.apache.commons.beanutils или java.beans), которая примет имя поля строки и преобразует ее в стандартное имя метода? Я смотрю повсюду и не могу найти простую утилиту преобразования строк.
Java: стандартная библиотека для преобразования имени поля ( "firstName" ) в имя метода доступа ( "getFirstName" )
Ответ 1
Появился дикий один лайнер!
String fieldToGetter(String name)
{
return "get" + name.substring(0, 1).toUpperCase() + name.substring(1);
}
Ответ 2
интроспектор JavaBean, возможно, лучший выбор. Он обрабатывает "is" getters для булевых типов и "getters", которые принимают аргумент и сеттеры с одним или двумя аргументами и другими случаями краев. Это полезно для получения списка полей JavaBean для класса.
Вот пример,
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() );
}
}
Отпечатает
class
name
size
class
происходит от getClass()
, унаследованного от Object
EDIT: получить получателя или сеттер и его имя.
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);
}
Ответ 3
Вы можете использовать PropertyDescriptor
без Inspector
(это было предложено Питером):
final PropertyDescriptor propertyDescriptor =
new PropertyDescriptor("name", MyBean.class);
System.out.println("getter: " + propertyDescriptor.getReadMethod().getName());
System.out.println("setter: " + propertyDescriptor.getWriteMethod().getName());
Ответ 4
String fieldToSetter(String name)
{
return "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
}
С авторским правом Matt Ball
Ответ 5
Я изменил приведенные выше методы, чтобы удалить символ подчеркивания и использовать следующий символ... например, если имя поля "validated_id", то имя метода getter будет "getValidatedId"
private String fieldToGetter(String name) {
Matcher matcher = Pattern.compile("_(\\w)").matcher(name);
while (matcher.find()) {
name = name.replaceFirst(matcher.group(0), matcher.group(1).toUpperCase());
}
return "get" + name.substring(0, 1).toUpperCase() + name.substring(1);
}
private String fieldToSetter(String name) {
Matcher matcher = Pattern.compile("_(\\w)").matcher(name);
while (matcher.find()) {
name = name.replaceFirst(matcher.group(0), matcher.group(1).toUpperCase());
}
return "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
}
Ответ 6
В следующем примере два поля с именем example
и example
имеют геттеры
getExample
и geteExample
IF, сгенерированные eclipse. НО это несовместимо с PropertyDescriptor("eXample",...).getReadMethod().getName()
, который ожидает getExample
как действительное имя получателя.
public class XX {
private Integer example;
private Integer eXample;
public Integer getExample() {
return example;
}
public Integer geteXample() {
return eXample;
}
public void setExample(Integer example) {
this.example = example;
}
public void seteXample(Integer eXample) {
this.eXample = eXample;
}
public static void main(String[] args) {
try {
System.out.println("Getter: " + new PropertyDescriptor("example", ReflTools.class).getReadMethod().getName());
System.out.println("Getter: " + new PropertyDescriptor("eXample", ReflTools.class).getReadMethod().getName());
} catch (IntrospectionException e) {
e.printStackTrace();
}
}
}
Ответ 7
Guava CaseFormat сделает это за вас.
Например, из lower_underscore → LowerUnderscore
CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, str)
Ответ 8
String fieldToGetter(Field field) {
final String name = field.getName();
final boolean isBoolean = (field.getType() == Boolean.class || field.getType() == boolean.class);
return (isBoolean ? "is" : "get") + name.substring(0, 1).toUpperCase() + name.substring(1);
}
String fieldToGetter(boolean isBoolean, String name) {
return (isBoolean ? "is" : "get") + name.substring(0, 1).toUpperCase() + name.substring(1);
}