Java examples for Reflection:Class
Find the most specialized class from group compatible with clazz.
/*//from ww w . j a v a 2s .c o m * Copyright (c) 2012 Data Harmonisation Panel * * All rights reserved. This program and the accompanying materials are made * available under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution. If not, see <http://www.gnu.org/licenses/>. * * Contributors: * HUMBOLDT EU Integrated Project #030962 * Data Harmonisation Panel <http://www.dhpanel.eu> */ //package com.java2s; import java.util.Collection; public class Main { /** * <p> * Find the most specialized class from group compatible with clazz. A * direct superclass match is searched and returned if found. * </p> * <p> * If not and checkAssignability is true, the most derived assignable class * is being searched. * </p> * <p> * See The Java Language Specification, sections 5.1.1 and 5.1.4 , for * details. * </p> * * @param clazz a class * @param group a collection of classes to match against * @param checkAssignability whether to use assignability when no direct * match is found * @return null or the most specialized match from group */ public static Class<?> findMostSpecificMatch(Class<?> clazz, Collection<Class<?>> group, boolean checkAssignability) { if (clazz == null || group == null) throw new IllegalArgumentException(""); //$NON-NLS-1$ // scale up the type hierarchy until we have found a matching class for (Class<?> c = clazz; c != Object.class; c = c.getSuperclass()) { if (group.contains(c)) return c; } if (checkAssignability) { // in lieu of a direct match, check assignability (likely clazz is // an interface) Class<?> result = null; for (Class<?> c : group) { if (clazz.isAssignableFrom(c)) { // result null or less specialized -> overwrite if (result == null || result.isAssignableFrom(c)) result = c; } } return result; } else { return null; } } }