简体   繁体   中英

java get getter/setter name from property name

I have some like this:

String getterName = "get"+StringUtils.capitalize(propertyName);
Method methodLabel = item.getClass().getMethod(getterName);

I know that this does not always work because properties like: "X" "x" etc... are diferent rules.

¿is there a method in the JAVA API to pass name property to getter/setter name?

I don't want to use: PropertyDescriptor. It requires to work both setter and getter.

EDIT:

What I want is this:

String propertyName ="money";
String getterPropertyNameByConventionJava = ConvertPropertyNameToGetterName(propertyName);
System.out.println(getterPropertyNameByConventionJava);
//prints getMoney or getMoney() anyway.

I have made my own solution since I see that there is not official implementation:

public static void main(String[] args) throws Exception {
        System.out.println("get"+cuerpoGetterSetter("probando0"));
        System.out.println("get"+cuerpoGetterSetter("x"));
        System.out.println("get"+cuerpoGetterSetter("X"));
        System.out.println("get"+cuerpoGetterSetter("URL"));
        System.out.println("get"+cuerpoGetterSetter("xIndex"));
    }
    public static String cuerpoGetterSetter(String propiedad) {
        if (propiedad == null || propiedad.length() == 0) {
            return propiedad;
        }
        if (propiedad.length() == 1) {
            return propiedad.toUpperCase();
        }
        if (Character.isUpperCase(propiedad.charAt(0))) {
            return propiedad;
        }
        if (propiedad.length() > 1 && Character.isUpperCase(propiedad.charAt(1))) {
            return propiedad;
        }
        return propiedad.substring(0, 1).toUpperCase() + propiedad.substring(1, propiedad.length());
    }

Results:

getProbando0
getX
getX
getURL
getxIndex

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM