1 package org.openrdf.elmo.impl;
2
3 import java.lang.reflect.Method;
4 import java.lang.reflect.Modifier;
5
6 import org.openrdf.elmo.ElmoBehaviourFactory;
7 import org.openrdf.elmo.Entity;
8 import org.openrdf.elmo.exceptions.ElmoInitializationException;
9
10 public class MethodFactory<T> implements ElmoBehaviourFactory<T> {
11 private Method method;
12 private Class<?> factoryClass;
13 private Method getInstance;
14
15 public MethodFactory(Method method, Class<?> factoryClass) {
16 assert method.getDeclaringClass().isAssignableFrom(factoryClass) : factoryClass
17 .getSimpleName()
18 + method;
19 this.method = method;
20 this.factoryClass = factoryClass;
21 this.getInstance = findInstanceMethod(factoryClass, method);
22 }
23
24 public Method getMethod() {
25 return method;
26 }
27
28 public Class<?> getFactoryClass() {
29 return factoryClass;
30 }
31
32 public Class<T> getBehaviourClass() {
33 return (Class<T>) method.getReturnType();
34 }
35
36 public T createBehaviour(Entity bean) {
37 try {
38 if (method.getParameterTypes().length == 0)
39 return (T) method.invoke(getFactoryInstance());
40 return (T) method.invoke(getFactoryInstance(), bean);
41 } catch (Exception e) {
42 throw new ElmoInitializationException(e);
43 }
44 }
45
46 private Method findInstanceMethod(Class<?> factoryClass, Method method) {
47 try {
48 Method getInstance = factoryClass.getDeclaredMethod("getInstance");
49 if (!Modifier.isStatic(getInstance.getModifiers()))
50 return null;
51 Class<?> declaring = method.getDeclaringClass();
52 if (declaring.isAssignableFrom(getInstance.getReturnType()))
53 return getInstance;
54 } catch (NoSuchMethodException e) {
55 }
56 return null;
57 }
58
59 private Object getFactoryInstance() throws Exception {
60 if (getInstance != null)
61 return getInstance.invoke(null);
62 return factoryClass.newInstance();
63 }
64
65 }