MentaContainer

Rev

Rev 88 | Rev 105 | 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
 
88 soliveira 5
import org.mentacontainer.Factory;
32 soliveira 6
import org.mentacontainer.util.FindMethod;
7
 
88 soliveira 8
public class GenericFactory implements Factory {
32 soliveira 9
 
10
        private final Object factory;
11
 
12
        private final Method method;
13
 
91 soliveira 14
        private final Class<? extends Object> type;
15
 
16
        public GenericFactory(Object factory, String methodName, Class<? extends Object> type) {
32 soliveira 17
 
18
                this.factory = factory;
19
 
91 soliveira 20
                this.type = type;
21
 
32 soliveira 22
                try {
23
 
24
                        this.method = FindMethod.getMethod(factory.getClass(), methodName, new Class[] { });
25
 
26
                        this.method.setAccessible(true);
27
 
28
                } catch(Exception e) {
29
 
30
                        throw new RuntimeException(e);
31
                }
32
        }
33
 
84 soliveira 34
        @Override
41 soliveira 35
        public <T> T getInstance()  {
32 soliveira 36
 
37
                try {
52 soliveira 38
 
41 soliveira 39
                        return (T) 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
49
        public Class<? extends Object> getType() {
50
                return type;
51
        }
32 soliveira 52
}