1
2
3
4 package org.opentrafficsim.water;
5
6 import java.io.Serializable;
7 import java.lang.reflect.Constructor;
8 import java.lang.reflect.Method;
9 import java.util.HashMap;
10 import java.util.Map;
11
12 import org.djutils.reflection.ClassUtil;
13
14 import nl.tudelft.simulation.dsol.SimRuntimeException;
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 public class SchedulableMethod implements Serializable
31 {
32
33 private static final long serialVersionUID = 1L;
34
35
36 @SuppressWarnings("checkstyle:visibilitymodifier")
37 protected Object target = null;
38
39
40 @SuppressWarnings("checkstyle:visibilitymodifier")
41 protected String method = null;
42
43
44 @SuppressWarnings("checkstyle:visibilitymodifier")
45 protected Object[] args = null;
46
47
48 private static Map<String, Method> cacheMethods = new HashMap<String, Method>();
49
50
51
52
53
54
55
56 public SchedulableMethod(final Object target, final String method, final Object[] args)
57 {
58 if (target == null || method == null)
59 {
60 throw new IllegalArgumentException("target or method==null");
61 }
62 this.target = target;
63 this.method = method;
64 this.args = args;
65 }
66
67
68
69
70 public final synchronized void execute()
71 {
72 try
73 {
74 if (this.method.equals("<init>"))
75 {
76 if (!(this.target instanceof Class))
77 {
78 throw new SimRuntimeException("Invoking a constructor implies that target should be instance of Class");
79 }
80 Constructor<?> constructor = ClassUtil.resolveConstructor((Class<?>) this.target, this.args);
81 constructor.setAccessible(true);
82 constructor.newInstance(this.args);
83 }
84 else
85 {
86 String key = this.target.getClass().getName() + "_" + this.method;
87 Method tm = cacheMethods.get(key);
88 if (tm == null)
89 {
90 tm = ClassUtil.resolveMethod(this.target, this.method, this.args);
91 cacheMethods.put(key, tm);
92 }
93 tm.setAccessible(true);
94 tm.invoke(this.target, this.args);
95 }
96 }
97 catch (Exception exception)
98 {
99 exception.printStackTrace();
100 }
101 }
102
103
104
105
106 public final Object[] getArgs()
107 {
108 return this.args;
109 }
110
111
112
113
114 public final String getMethod()
115 {
116 return this.method;
117 }
118
119
120
121
122 public final Object getTarget()
123 {
124 return this.target;
125 }
126
127
128 @Override
129 public final String toString()
130 {
131 return "SchedulableMethod[target=" + this.target + "; method=" + this.method + "; args=" + this.args + "]";
132 }
133
134 }