01: package biz.hammurapi.config;
02:
03: import java.lang.reflect.InvocationHandler;
04: import java.lang.reflect.Method;
05: import java.lang.reflect.Proxy;
06:
07: /**
08: * This is a dynamic proxy wrapper for one component to obtain a reference to another.
09: * @author Pavel Vlasov
10: */
11: public class Reference implements Wrapper, Component {
12:
13: private Object master;
14:
15: /**
16: * Proxy to the master. Master may not exist at the time of proxy creation.
17: */
18: private Object proxy;
19:
20: public Object getMaster() {
21: return proxy;
22: }
23:
24: private Object owner;
25:
26: public void setOwner(Object owner) {
27: this .owner = owner;
28: }
29:
30: public void start() throws ConfigurationException {
31: if (owner instanceof Context) {
32: master = ((Context) owner).get(path);
33: if (master == null) {
34: throw new ConfigurationException(
35: "Master is null, path: " + path);
36: }
37: } else {
38: throw new ConfigurationException(
39: "Owner does not implement "
40: + Context.class.getName());
41: }
42: }
43:
44: public void stop() throws ConfigurationException {
45: // TODO Auto-generated method stub
46:
47: }
48:
49: /**
50: * Interface which dynamic proxy shall implement.
51: * @param type
52: * @throws ClassNotFoundException
53: */
54: public void setType(String type) throws ClassNotFoundException {
55: InvocationHandler ih = new InvocationHandler() {
56:
57: public Object invoke(Object proxy, Method method,
58: Object[] args) throws Throwable {
59: if (master == null) {
60: throw new IllegalStateException(
61: "Master is null, path: " + path);
62: }
63: return method.invoke(master, args);
64: }
65:
66: };
67:
68: proxy = Proxy.newProxyInstance(
69: this .getClass().getClassLoader(), new Class[] { Class
70: .forName(type) }, ih);
71: }
72:
73: private String path;
74:
75: /**
76: * Path to the referenced component
77: * @param path
78: */
79: public void setPath(String path) {
80: this.path = path;
81: }
82:
83: }
|