d076ae96 |
1 | /* |
2 | * To change this template, choose Tools | Templates |
3 | * and open the template in the editor. |
4 | */ |
5 | package org.ufcspa.simdecs.diagram.util; |
6 | |
d076ae96 |
7 | import java.io.File; |
8 | import java.io.IOException; |
9 | import java.lang.reflect.Field; |
10 | import java.lang.reflect.Method; |
11 | import java.net.URL; |
12 | import java.util.ArrayList; |
13 | import java.util.Enumeration; |
14 | import java.util.List; |
248a4c16 |
15 | import org.apache.commons.lang3.text.WordUtils; |
d076ae96 |
16 | |
17 | /** |
18 | * |
19 | * @author maroni |
20 | */ |
21 | public class ReflectionUtils { |
22 | |
23 | public static Class[] getClasses(String packageName) throws ClassNotFoundException, IOException { |
24 | ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); |
25 | assert classLoader != null; |
26 | String path = packageName.replace('.', '/'); |
27 | Enumeration<URL> resources = classLoader.getResources(path); |
28 | List<File> dirs = new ArrayList<File>(); |
29 | while (resources.hasMoreElements()) { |
30 | URL resource = resources.nextElement(); |
31 | dirs.add(new File(resource.getFile())); |
32 | } |
33 | ArrayList<Class> classes = new ArrayList<Class>(); |
34 | for (File directory : dirs) { |
35 | classes.addAll(findClasses(directory, packageName)); |
36 | } |
37 | return classes.toArray(new Class[classes.size()]); |
38 | } |
39 | |
40 | private static List<Class> findClasses(File directory, String packageName) throws ClassNotFoundException { |
41 | List<Class> classes = new ArrayList<Class>(); |
42 | if (!directory.exists()) { |
43 | return classes; |
44 | } |
45 | File[] files = directory.listFiles(); |
46 | for (File file : files) { |
47 | if (file.isDirectory()) { |
48 | assert !file.getName().contains("."); |
49 | classes.addAll(findClasses(file, packageName + "." + file.getName())); |
50 | } else if (file.getName().endsWith(".class")) { |
51 | classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6))); |
52 | } |
53 | } |
54 | return classes; |
55 | } |
56 | |
57 | public static Method getSetterMethod(Class reflectClass, Field field) { |
58 | for (Method method : reflectClass.getMethods()) { |
248a4c16 |
59 | if (method.getName().equals("set" + WordUtils.capitalize(field.getName()))) { |
d076ae96 |
60 | return method; |
61 | } |
62 | } |
63 | |
64 | return null; |
65 | } |
66 | |
67 | public static Method getGetterMethod(Class reflectClass, Field field) { |
68 | for (Method method : reflectClass.getMethods()) { |
248a4c16 |
69 | if (method.getName().equals("get" + WordUtils.capitalize(field.getName()))) { |
d076ae96 |
70 | return method; |
71 | } |
72 | } |
73 | |
74 | return null; |
75 | } |
76 | |
77 | } |