OnJava8-Examples/generics/DynamicProxyMixin.java

66 lines
2.0 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// generics/DynamicProxyMixin.java
2015-12-15 11:47:04 -08:00
// (c)2016 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2015-06-15 17:47:35 -07:00
import java.lang.reflect.*;
import java.util.*;
import onjava.*;
import static onjava.Tuple.*;
2015-06-15 17:47:35 -07:00
class MixinProxy implements InvocationHandler {
2016-01-25 18:05:55 -08:00
Map<String, Object> delegatesByMethod;
2015-06-15 17:47:35 -07:00
@SuppressWarnings("unchecked")
2016-01-25 18:05:55 -08:00
public MixinProxy(Tuple2<Object, Class<?>>... pairs) {
2015-06-15 17:47:35 -07:00
delegatesByMethod = new HashMap<>();
2016-01-25 18:05:55 -08:00
for(Tuple2<Object, Class<?>> pair : pairs) {
for(Method method : pair.a2.getMethods()) {
2015-06-15 17:47:35 -07:00
String methodName = method.getName();
// The first interface in the map
// implements the method.
if(!delegatesByMethod.containsKey(methodName))
delegatesByMethod.put(methodName, pair.a1);
2015-06-15 17:47:35 -07:00
}
}
}
@Override
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(Tuple2... pairs) {
2015-06-15 17:47:35 -07:00
Class[] interfaces = new Class[pairs.length];
for(int i = 0; i < pairs.length; i++) {
interfaces[i] = (Class)pairs[i].a2;
2015-06-15 17:47:35 -07:00
}
ClassLoader cl =
pairs[0].a1.getClass().getClassLoader();
2015-06-15 17:47:35 -07:00
return Proxy.newProxyInstance(
cl, interfaces, new MixinProxy(pairs));
}
}
public class DynamicProxyMixin {
public static void main(String[] args) {
Object mixin = MixinProxy.newInstance(
tuple(new BasicImp(), Basic.class),
tuple(new TimeStampedImp(), TimeStamped.class),
2016-01-25 18:05:55 -08:00
tuple(new SerialNumberedImp(),
SerialNumbered.class));
2015-06-15 17:47:35 -07:00
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());
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
Hello
2016-07-27 11:12:11 -06:00
1469638238271
2015-06-15 17:47:35 -07:00
1
2015-09-07 11:44:36 -06:00
*/