fee901957bd3337b46550fd935edd22307a6a48a
[simdecs.git] / src / java / org / ufcspa / simdecs / diagram / util / ReflectionUtils.java
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
7 import com.sun.xml.internal.ws.util.StringUtils;
8 import java.io.File;
9 import java.io.IOException;
10 import java.lang.reflect.Field;
11 import java.lang.reflect.Method;
12 import java.net.URL;
13 import java.util.ArrayList;
14 import java.util.Enumeration;
15 import java.util.List;
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()) {
59             if (method.getName().equals("set" + StringUtils.capitalize(field.getName()))) {
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()) {
69             if (method.getName().equals("get" + StringUtils.capitalize(field.getName()))) {
70                 return method;
71             }
72         }
73         
74         return null;
75     }
76     
77 }