Andreas Dolk
Andreas Dolk

Reputation: 114817

Convert single char in String to lower case

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?

Upvotes: 14

Views: 23385

Answers (6)

DeadDingo
DeadDingo

Reputation: 21

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 :)

Upvotes: 2

Peter Lawrey
Peter Lawrey

Reputation: 533870

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().

Upvotes: 2

Tim Büthe
Tim Büthe

Reputation: 63814

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();
}

Upvotes: 3

McDowell
McDowell

Reputation: 108969

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.

Upvotes: 3

Paul Brinkley
Paul Brinkley

Reputation: 6363

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.

Upvotes: 0

Valentin Rocher
Valentin Rocher

Reputation: 11669

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

Upvotes: 4

Related Questions