001/* 002 * (C) Copyright 2006-2011 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * bstefanescu 018 * 019 * $Id$ 020 */ 021 022package org.nuxeo.common.collections; 023 024import java.util.HashMap; 025 026/** 027 * A Class keyed map sensitive to class hierarchy. This map provides an additional method {@link #find(Class)} that can 028 * be used to lookup a class compatible to the given one depending on the class hierarchy. 029 * 030 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a> 031 */ 032public class ClassMap<T> extends HashMap<Class<?>, T> { 033 034 private static final long serialVersionUID = 1L; 035 036 public T find(Class<?> key) { 037 T v = get(key); 038 if (v == null) { 039 Class<?> sk = key.getSuperclass(); 040 if (sk != null) { 041 v = get(sk); 042 } 043 Class<?>[] itfs = null; 044 if (v == null) { // try interfaces 045 itfs = key.getInterfaces(); 046 for (Class<?> itf : itfs) { 047 v = get(itf); 048 if (v != null) { 049 break; 050 } 051 } 052 } 053 if (v == null) { 054 if (sk != null) { // superclass 055 v = find(sk); 056 } 057 if (v == null) { // interfaces 058 for (Class<?> itf : itfs) { 059 v = find(itf); 060 if (v != null) { 061 break; 062 } 063 } 064 } 065 } 066 if (v != null) { 067 put(key, v); 068 } 069 } 070 return v; 071 } 072 073}