tags:

views:

344

answers:

6

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?

+3  A: 

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

Valentin Rocher
+2  A: 

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
This would yield "someattribute" instead of "someAttribute".
Paul Brinkley
just saw, fixed that by suggesting commons lang
Tim Büthe
I think that's what I'm going to do. Even though it's the same solution 'under the hood'. Can't vote up, because I've not enough reputation yet. So please accept my verbose thumbs up!
Andreas_D
+1 for commons-lang - why reinvent the wheel?
David Rabinowitz
A: 

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
+5  A: 

I think your solution is just fine. I dont think there is any easier way to do it.

Josh Curren
+2  A: 

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
+1  A: 

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