1 | |
package nl.beesting.beangenerator.locators; |
2 | |
|
3 | |
import java.util.List; |
4 | |
import java.lang.reflect.Method; |
5 | |
|
6 | |
import nl.beesting.beangenerator.config.BeanGeneratorConfig; |
7 | |
import nl.beesting.beangenerator.config.BeanGeneratorConfigParser; |
8 | |
import nl.beesting.beangenerator.config.ClassDescriptor; |
9 | |
import nl.beesting.beangenerator.config.InstanceGeneratorDescriptor; |
10 | |
|
11 | |
import org.aopalliance.intercept.MethodInvocation; |
12 | |
import org.apache.commons.lang.StringUtils; |
13 | |
|
14 | 4 | public class ConfigurationClassLocator implements ClassLocator { |
15 | |
private BeanGeneratorConfig configuration; |
16 | |
|
17 | |
public void setConfigParser(BeanGeneratorConfigParser configParser) { |
18 | 3 | this.configuration = configParser.getConfiguration(); |
19 | 3 | } |
20 | |
|
21 | |
public Class<?> findClass(MethodInvocation invocation) { |
22 | 8 | Class<?> result = null; |
23 | 8 | Class<?> returnType = invocation.getMethod().getReturnType(); |
24 | 8 | List<ClassDescriptor> definitions = configuration.getClassDefinitions(); |
25 | 8 | for (ClassDescriptor classDescriptor : definitions) { |
26 | 19 | Class<?> clazz = classDescriptor.getClazz(); |
27 | 19 | if (clazz.equals(returnType)) { |
28 | 3 | return clazz; |
29 | |
} |
30 | 16 | } |
31 | |
|
32 | 5 | InstanceGeneratorDescriptor defaultGenerator = configuration.getDefaultGenerator(returnType); |
33 | 5 | if (defaultGenerator != null) { |
34 | 0 | result = returnType; |
35 | |
} |
36 | |
|
37 | 5 | ClassDescriptor classDescriptor = null; |
38 | 5 | String name = null; |
39 | 5 | if (result == null) { |
40 | 5 | Method method = invocation.getMethod(); |
41 | 5 | name = getMethodName(method); |
42 | 5 | classDescriptor = configuration.getClassDefinitionByMethod(name); |
43 | 5 | if (classDescriptor == null) { |
44 | 2 | name = method.getName(); |
45 | 2 | classDescriptor = configuration.getClassDefinitionByMethod(name); |
46 | |
} |
47 | |
} |
48 | |
|
49 | 5 | if (classDescriptor != null) { |
50 | 3 | result = classDescriptor.getFieldDefinitions().get(name).getClazz(); |
51 | |
} |
52 | |
|
53 | |
|
54 | 5 | return result; |
55 | |
} |
56 | |
|
57 | |
private String getMethodName(Method method) { |
58 | 5 | String name = method.getName(); |
59 | 5 | if (name.startsWith("get") || name.startsWith("set")) { |
60 | 0 | name = StringUtils.uncapitalize(name.substring(3)); |
61 | |
} |
62 | |
|
63 | 5 | return name; |
64 | |
} |
65 | |
|
66 | |
} |