OnJava8-Examples/generics/DynamicProxyMixin.java

62 lines
1.9 KiB
Java
Raw Normal View History

2015-04-20 15:36:01 -07:00
//: generics/DynamicProxyMixin.java
2015-05-29 14:18:51 -07:00
// <20>2015 MindView LLC: see Copyright.txt
2015-04-20 15:36:01 -07:00
import java.lang.reflect.*;
import java.util.*;
import net.mindview.util.*;
import static net.mindview.util.Tuple.*;
class MixinProxy implements InvocationHandler {
Map<String,Object> delegatesByMethod;
2015-05-05 11:20:13 -07:00
@SuppressWarnings("unchecked")
2015-04-20 15:36:01 -07:00
public MixinProxy(TwoTuple<Object,Class<?>>... pairs) {
2015-05-05 11:20:13 -07:00
delegatesByMethod = new HashMap<>();
2015-04-20 15:36:01 -07:00
for(TwoTuple<Object,Class<?>> pair : pairs) {
for(Method method : pair.second.getMethods()) {
String methodName = method.getName();
// The first interface in the map
// implements the method.
2015-05-18 23:05:20 -07:00
if(!delegatesByMethod.containsKey(methodName))
2015-04-20 15:36:01 -07:00
delegatesByMethod.put(methodName, pair.first);
}
}
2015-05-18 23:05:20 -07:00
}
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
public Object invoke(Object proxy, Method method,
Object[] args) throws Throwable {
String methodName = method.getName();
Object delegate = delegatesByMethod.get(methodName);
return method.invoke(delegate, args);
}
@SuppressWarnings("unchecked")
public static Object newInstance(TwoTuple... pairs) {
Class[] interfaces = new Class[pairs.length];
for(int i = 0; i < pairs.length; i++) {
interfaces[i] = (Class)pairs[i].second;
}
ClassLoader cl =
pairs[0].first.getClass().getClassLoader();
return Proxy.newProxyInstance(
cl, interfaces, new MixinProxy(pairs));
}
2015-05-18 23:05:20 -07:00
}
2015-04-20 15:36:01 -07:00
public class DynamicProxyMixin {
public static void main(String[] args) {
Object mixin = MixinProxy.newInstance(
tuple(new BasicImp(), Basic.class),
tuple(new TimeStampedImp(), TimeStamped.class),
tuple(new SerialNumberedImp(),SerialNumbered.class));
Basic b = (Basic)mixin;
TimeStamped t = (TimeStamped)mixin;
SerialNumbered s = (SerialNumbered)mixin;
b.set("Hello");
System.out.println(b.get());
System.out.println(t.getStamp());
System.out.println(s.getSerialNumber());
}
} /* Output: (Sample)
Hello
1132519137015
1
*///:~