14

I like to 'guess' attribute names from getter methods. So 'getSomeAttribute' shall be converted to 'someAttribute'.

Usually I do something like

String attributeName = Character.toLowerCase(methodName.indexOf(3)) 
                       + methodName.substring(4);

Pretty ugly, right? I usually hide it in a method, but does anybody know a better solution?

Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
  • Why are you trying to guess the variable name? – Milhous May 12 '09 at 14:21
  • For a large application I want to auto generate a huge set of wsdl's and xml schema's to put a SOAP interface next to the existing JMS. Pretty difficult in this case - I have to parse source files and reflect libraries... At least there's a (custom) naming convention for attributes and getter, so with the method name I can test or reflect some fields – Andreas Dolk May 12 '09 at 14:32
  • If you can use refection, then you can get the actual variable names. – Milhous May 12 '09 at 17:14

6 Answers6

4

The uncapitalize method of Commons Lang shall help you, but I don't think your solution is so crude.

Valentin Rocher
  • 11,667
  • 45
  • 59
3

uncapitalize from commons lang would do it:

String attributeName = StringUtils.uncapitalize(methodName.substring(3));

I need commons lang a lot, but if you don't like that extra jar, you could copy the method. As you can see in it, they doin' it like you:

public static String uncapitalize(String str) {
    int strLen;
    if (str == null || (strLen = str.length()) == 0) {
        return str;
    }
    return new StringBuffer(strLen)
        .append(Character.toLowerCase(str.charAt(0)))
        .append(str.substring(1))
        .toString();
}
Tim Büthe
  • 62,884
  • 17
  • 92
  • 129
3

Have a look at the JavaBeans API:

BeanInfo info = Introspector.getBeanInfo(bean
       .getClass(), Object.class);
for (PropertyDescriptor propertyDesc : info
       .getPropertyDescriptors()) {
  String name = propertyDesc.getName();
}

Also see decapitalize.

McDowell
  • 107,573
  • 31
  • 204
  • 267
2

Given a character buffer, you can apply the below code:

int i = 0;
for(char x : buffer) {
    buffer[i] = Character.toLowerCase(x);
    i++;
}

Tested and functions :)

DeadDingo
  • 21
  • 1
2

Its worth remembering that;

  • not all getXXX methods are getters e.g. double getSqrt(double x), void getup().
  • methods which return boolean, start with is and don't take an argument can be a getter, e.g. boolean isActive().
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

Looks fine to me. Yes, it looks verbose, but consider what you're trying to do, and what another programmer would think if they were trying to understand what this code is trying to do. If anything, I'd make it longer, by adding what you're doing (guessing attribute names from getter methods) as a comment.

Paul Brinkley
  • 6,283
  • 3
  • 24
  • 33