Reputation: 114817
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
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
Reputation: 533870
Its worth remembering that;
Upvotes: 2
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
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
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
Reputation: 11669
The uncapitalize method of Commons Lang shall help you, but I don't think your solution is so crude.
Upvotes: 4