Java:将字段名称(“firstName”)转换为访问器方法名称(“getFirstName”)的标准库
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5503412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: standard library to convert field name ("firstName") to accessor method name ("getFirstName")
提问by pconrey
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.
是否有标准库(例如 org.apache.commons.beanutils 或 java.beans)将采用字符串字段名称并将其转换为标准方法名称?我到处找,找不到一个简单的字符串转换实用程序。
回答by Peter Lawrey
The JavaBean introspectoris 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.
该JavaBean的内省可能是最好的选择。它处理布尔类型的“is”getter 和接受一个参数的“getter”和没有或两个参数和其他边缘情况的 setter。获取类的 JavaBean 字段列表非常有用。
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
class
来自getClass()
继承自Object
EDIT: to get the getter or setter and its name.
编辑:获取 getter 或 setter 及其名称。
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);
}
回答by Matt Ball
A wild one-liner appeared!
一只狂野的单线出现了!
String fieldToGetter(String name)
{
return "get" + name.substring(0, 1).toUpperCase() + name.substring(1);
}
回答by palacsint
You can use a PropertyDescriptor
without an Inspector
(which was suggested by Peter):
您可以使用 a PropertyDescriptor
without an Inspector
(这是 Peter 建议的):
final PropertyDescriptor propertyDescriptor =
new PropertyDescriptor("name", MyBean.class);
System.out.println("getter: " + propertyDescriptor.getReadMethod().getName());
System.out.println("setter: " + propertyDescriptor.getWriteMethod().getName());
回答by RoflcoptrException
String fieldToSetter(String name)
{
return "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
}
With copyright by Matt Ball
马特·鲍尔版权所有
回答by Adrián Rivero
I modified the methods above, to remove the underscore character and capitalize the next character... for instance, if the field name is "validated_id", then the getter method name will be "getValidatedId"
我修改了上面的方法,删除下划线字符并将下一个字符大写......例如,如果字段名称是“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);
}
回答by Jasmeet Singh
Guava CaseFormat will do it for you.
Guava CaseFormat 将为您完成。
For example from lower_underscore -> LowerUnderscore
例如从lower_underscore -> LowerUnderscore
CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, str)
回答by Majid Asgari-Bidhendi
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);
}
回答by Petros Makris
In the following example two fields named example
and eXample
have the getters
getExample
and geteExample
IFgenerated by eclipse. BUT this is not compatible with PropertyDescriptor("eXample",...).getReadMethod().getName()
which expects getEXample
as a valid getter name.
在下面的示例中,两个字段命名example
并eXample
具有由 eclipse 生成的 getter
getExample
和geteExample
IF。但是这与PropertyDescriptor("eXample",...).getReadMethod().getName()
期望getEXample
为有效 getter 名称的不兼容。
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();
}
}
}