01: /*
02: * Copyright (C) 2005 Joe Walnes.
03: * Copyright (C) 2006, 2007, 2008 XStream Committers.
04: * All rights reserved.
05: *
06: * The software in this package is published under the terms of the BSD
07: * style license a copy of which has been included with this distribution in
08: * the LICENSE.txt file.
09: *
10: * Created on 22. January 2005 by Joe Walnes
11: */
12: package com.thoughtworks.xstream.mapper;
13:
14: import com.thoughtworks.xstream.alias.ClassMapper;
15:
16: import java.lang.ref.WeakReference;
17: import java.util.Collections;
18: import java.util.HashMap;
19: import java.util.Map;
20:
21: /**
22: * Mapper that caches which names map to which classes. Prevents repetitive searching and class loading.
23: *
24: * @author Joe Walnes
25: */
26: public class CachingMapper extends MapperWrapper {
27:
28: private transient Map realClassCache;
29:
30: public CachingMapper(Mapper wrapped) {
31: super (wrapped);
32: readResolve();
33: }
34:
35: /**
36: * @deprecated As of 1.2, use {@link #CachingMapper(Mapper)}
37: */
38: public CachingMapper(ClassMapper wrapped) {
39: this ((Mapper) wrapped);
40: readResolve();
41: }
42:
43: public Class realClass(String elementName) {
44: WeakReference reference = (WeakReference) realClassCache
45: .get(elementName);
46: if (reference != null) {
47: Class cached = (Class) reference.get();
48: if (cached != null) {
49: return cached;
50: }
51: }
52:
53: Class result = super .realClass(elementName);
54: realClassCache.put(elementName, new WeakReference(result));
55: return result;
56: }
57:
58: private Object readResolve() {
59: realClassCache = Collections.synchronizedMap(new HashMap(128));
60: return this;
61: }
62:
63: }
|