MentaContainer

Rev

Rev 141 | Rev 143 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
32 soliveira 1
package org.mentacontainer.impl;
2
 
3
import java.lang.reflect.Method;
4
 
141 soliveira 5
import org.mentacontainer.Creator;
32 soliveira 6
import org.mentacontainer.util.FindMethod;
7
 
142 soliveira 8
public class GenericFactory<E> implements Creator<E> {
32 soliveira 9
 
10
        private final Object factory;
11
 
12
        private final Method method;
13
 
141 soliveira 14
        private final Class<E> type;
91 soliveira 15
 
105 soliveira 16
        public GenericFactory(Object factory, String methodName) {
32 soliveira 17
 
18
                this.factory = factory;
19
 
20
                try {
21
 
22
                        this.method = FindMethod.getMethod(factory.getClass(), methodName, new Class[] { });
23
 
24
                        this.method.setAccessible(true);
25
 
141 soliveira 26
                        this.type = (Class<E>) method.getReturnType();
105 soliveira 27
 
32 soliveira 28
                } catch(Exception e) {
29
 
30
                        throw new RuntimeException(e);
31
                }
32
        }
33
 
84 soliveira 34
        @Override
141 soliveira 35
        public E createInstance()  {
32 soliveira 36
 
37
                try {
52 soliveira 38
 
141 soliveira 39
                        return (E) method.invoke(factory, (Object[]) null);
32 soliveira 40
 
40 soliveira 41
                } catch(Exception e) {
32 soliveira 42
 
40 soliveira 43
                        throw new RuntimeException("Cannot invoke method: " + method, e);
32 soliveira 44
 
40 soliveira 45
                }
32 soliveira 46
        }
91 soliveira 47
 
48
        @Override
141 soliveira 49
        public Class<E> getType() {
91 soliveira 50
                return type;
51
        }
32 soliveira 52
}