MentaContainer

Rev

Rev 146 | 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
 
143 soliveira 5
import org.mentacontainer.Factory;
146 soliveira 6
import org.mentacontainer.Interceptor;
32 soliveira 7
import org.mentacontainer.util.FindMethod;
8
 
146 soliveira 9
public class GenericFactory<E> implements Factory, Interceptor<E> {
32 soliveira 10
 
11
        private final Object factory;
12
 
146 soliveira 13
        private final Method method;
32 soliveira 14
 
148 soliveira 15
        private final Class<?> type;
91 soliveira 16
 
146 soliveira 17
        private Interceptor<E> interceptor = null;
18
 
19
        public GenericFactory(Object factory, String methodName) {
32 soliveira 20
 
21
                this.factory = factory;
22
 
23
                try {
24
 
146 soliveira 25
                        this.method = FindMethod.getMethod(factory.getClass(), methodName, new Class[] { });
32 soliveira 26
 
146 soliveira 27
                        this.method.setAccessible(true);
32 soliveira 28
 
146 soliveira 29
                        this.type = method.getReturnType();
105 soliveira 30
 
32 soliveira 31
                } catch(Exception e) {
32
 
33
                        throw new RuntimeException(e);
34
                }
35
        }
36
 
146 soliveira 37
        public void setInterceptor(Interceptor<E> interceptor) {
38
 
39
                this.interceptor = interceptor;
40
        }
41
 
84 soliveira 42
        @Override
146 soliveira 43
        public void onCreated(E createdObject) {
44
                if (interceptor != null) {
45
                        interceptor.onCreated(createdObject);
46
                }
47
        }
48
 
49
        @Override
50
        public void onCleared(E clearedObject) {
51
                if (interceptor != null) {
52
                        interceptor.onCleared(clearedObject);
53
                }
54
        }
55
 
56
        @Override
57
        public <T> T getInstance()  {
32 soliveira 58
 
59
                try {
52 soliveira 60
 
146 soliveira 61
                        return (T) method.invoke(factory, (Object[]) null);
32 soliveira 62
 
40 soliveira 63
                } catch(Exception e) {
32 soliveira 64
 
146 soliveira 65
                        throw new RuntimeException("Cannot invoke method: " + method, e);
32 soliveira 66
 
40 soliveira 67
                }
32 soliveira 68
        }
91 soliveira 69
 
70
        @Override
148 soliveira 71
        public Class<?> getType() {
91 soliveira 72
                return type;
73
        }
32 soliveira 74
}