Project

General

Profile

Download (1.91 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
 * 
3
 */
4
package eu.etaxonomy.taxeditor.singlesource;
5

    
6
import java.lang.reflect.Constructor;
7
import java.lang.reflect.InvocationTargetException;
8
import java.util.ArrayList;
9

    
10
import org.apache.log4j.Logger;
11

    
12
/**
13
 * @author Lutz Suhrbier
14
 * 
15
 */
16
public class ImplementationLoader {
17
	private static final Logger logger = Logger.getLogger(ImplementationLoader.class);
18

    
19
	public static Object newInstance(final Class<?> type, final Object... parameter) throws ClassNotFoundException {
20
		String className = type.getName() + "Impl";
21
		Object result = null;
22
		logger.debug("Loading class " + className);
23
		Class clazz = type.getClassLoader().loadClass(className);
24
		try {
25
			if (parameter.length > 0) {
26
				ArrayList<Class<?>> parameterList = new ArrayList<Class<?>>();
27
				for (Object o : parameter) {
28
					parameterList.add(o.getClass());
29
				}
30
				Class<?>[] parameterTypes = (Class<?>[]) parameterList.toArray(new Class<?>[parameter.length]);
31
				Constructor constructor = getPossibleConstructor(clazz,	parameterTypes);
32
				logger.debug("Constructor " + constructor + " found for class " +  className);
33
				result = constructor.newInstance(parameter);
34
			} else
35
				result = clazz.newInstance();
36
		} catch (IllegalArgumentException e) {
37
			e.printStackTrace();
38
		} catch (InstantiationException e) {
39
			e.printStackTrace();
40
		} catch (IllegalAccessException e) {
41
			e.printStackTrace();
42
		} catch (InvocationTargetException e) {
43
			e.printStackTrace();
44
		}
45
		return result;
46
	}
47

    
48
	public static Constructor getPossibleConstructor(Class motherClass,	Class[] pars) {
49

    
50
		Constructor[] ctors = motherClass.getConstructors();
51
		for (Constructor c : ctors) {
52
			Class[] cpars = c.getParameterTypes();
53
			if (cpars.length != pars.length)
54
				continue;
55
			boolean found = true;
56

    
57
			for (int i = 0; i < cpars.length; ++i) {
58
				if (!cpars[i].isAssignableFrom(pars[i])) {
59
					found = false;
60
					break;
61
				}
62
			}
63

    
64
			if (found)
65
				return c;
66
		}
67
		return null;
68
	}
69
}
    (1-1/1)