View Javadoc
1   package org.pojomatic.internal;
2   
3   import java.lang.reflect.Method;
4   
5   public class PropertyAccessor extends AbstractPropertyElement<Method> {
6     private final static String GET = "get", IS = "is";
7   
8     public PropertyAccessor(Method method, String name) {
9       super(method, name.length() == 0 ? getName(method) : name);
10    }
11  
12    private static String getName(Method method) {
13      String methodName = method.getName();
14      if (isPrefixedWith(methodName, GET)) {
15        return decapitalize(methodName.substring(GET.length()));
16      }
17      else if (isBoolean(method.getReturnType()) && isPrefixedWith(methodName, IS)) {
18        return decapitalize(methodName.substring(IS.length()));
19      }
20      else {
21        return methodName;
22      }
23    }
24  
25    private static boolean isBoolean(Class<?> clazz) {
26      return Boolean.class.equals(clazz) || Boolean.TYPE.equals(clazz);
27    }
28  
29    private static boolean isPrefixedWith(String name, String prefix) {
30      return name.length() > prefix.length()
31      && name.startsWith(prefix)
32      && Character.isUpperCase(name.charAt(prefix.length()));
33    }
34  
35    @Override
36    public String getElementName() {
37      return element.getName();
38    }
39  
40    @Override
41    public String getType() {
42      return "method";
43    }
44  
45    @Override
46    public Class<?> getPropertyType() {
47      return element.getReturnType();
48    }
49  
50    private static String decapitalize(String name) {
51      if (name.length() > 1 && Character.isUpperCase(name.charAt(1)) &&
52                      Character.isUpperCase(name.charAt(0))){
53          return name;
54      }
55      char chars[] = name.toCharArray();
56      chars[0] = Character.toLowerCase(chars[0]);
57      return new String(chars);
58    }
59  }