MentaContainer

Rev

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