1/******************************************************************************* 2 * Copyright (c) 2011 Google, Inc. 3 * All rights reserved. This program and the accompanying materials 4 * are made available under the terms of the Eclipse Public License v1.0 5 * which accompanies this distribution, and is available at 6 * http://www.eclipse.org/legal/epl-v10.html 7 * 8 * Contributors: 9 * Google, Inc. - initial API and implementation 10 *******************************************************************************/ 11package org.eclipse.wb.internal.core.utils.reflect; 12 13import java.util.HashMap; 14import java.util.Map; 15 16/** 17 * {@link Map}-like interface for mapping {@link Class} to value. 18 * 19 * @author scheglov_ke 20 * @coverage core.util 21 */ 22public final class ClassMap<V> { 23 //////////////////////////////////////////////////////////////////////////// 24 // 25 // Constructor 26 // 27 //////////////////////////////////////////////////////////////////////////// 28 /** 29 * Creates new instance of {@link ClassMap}. 30 */ 31 public static <V> ClassMap<V> create() { 32 return new ClassMap<V>(); 33 } 34 35 //////////////////////////////////////////////////////////////////////////// 36 // 37 // Map 38 // 39 //////////////////////////////////////////////////////////////////////////// 40 public void put(Class<?> key, V value) { 41 getMap(key).put(key, value); 42 } 43 44 public V get(Class<?> key) { 45 return getMap(key).get(key); 46 } 47 48 public void remove(Class<?> key) { 49 getMap(key).remove(key); 50 } 51 52 public void clear(ClassLoader classLoader) { 53 getMap(classLoader).clear(); 54 } 55 56 //////////////////////////////////////////////////////////////////////////// 57 // 58 // Implementation 59 // 60 //////////////////////////////////////////////////////////////////////////// 61 private Map<Class<?>, V> getMap(Class<?> key) { 62 ClassLoader classLoader = key.getClassLoader(); 63 return getMap(classLoader); 64 } 65 66 @SuppressWarnings("unchecked") 67 private Map<Class<?>, V> getMap(ClassLoader classLoader) { 68 Object map = ClassLoaderLocalMap.get(classLoader, this); 69 if (map == null) { 70 map = new HashMap<Class<?>, V>(); 71 ClassLoaderLocalMap.put(classLoader, this, map); 72 } 73 return (Map<Class<?>, V>) map; 74 } 75} 76