/*
 * This file is part of Nuts Framework.
 * Copyright(C) 2009-2012 Nuts Develop Team.
 *
 * Nuts Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License any later version.
 * 
 * Nuts Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
package nuts.core.lang;

import nuts.core.collections.CollectionUtils;

import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * ulitity class for Class
 */
public class ClassUtils extends org.apache.commons.lang3.ClassUtils {
	/** Suffix for array class names: "[]" */
	public final static String ARRAY_SUFFIX = "[]";

	/** The CGLIB class separator character "$$" */
	public final static String CGLIB_CLASS_SEPARATOR = "$$";

	/** The ".class" file suffix */
	public final static String CLASS_FILE_SUFFIX = ".class";


	/**
	 * Map with primitive wrapper type as key and corresponding primitive
	 * type as value, for example: Integer.class -> int.class.
	 */
	private final static Map<Class<?>, Class<?>> wrapper2PrimitiveTypeMap = new HashMap<Class<?>, Class<?>>(9);

	/**
	 * Map with primitive type as key and corresponding primitive wrapper
	 * type as value, for example: int.class -> Integer.class.
	 */
	private final static Map<Class<?>, Class<?>> primitive2WrapperTypeMap = new HashMap<Class<?>, Class<?>>(9);

	/**
	 * Map with primitive type as key and corresponding primitive type name as value,
	 * for example: int.class -> "int".
	 */
	private final static Map<Class<?>, String> primitiveTypeNameMap = new HashMap<Class<?>, String>(9);

	/**
	 * Map with primitive type as key and corresponding primitive wrapper name as value,
	 * for example: int.class -> "java.lang.Integer".
	 */
	private final static Map<Class<?>, String> primitiveWrapNameMap = new HashMap<Class<?>, String>(9);
	
	static {
		wrapper2PrimitiveTypeMap.put(Boolean.class, Boolean.TYPE);
		wrapper2PrimitiveTypeMap.put(Byte.class, Byte.TYPE);
		wrapper2PrimitiveTypeMap.put(Character.class, Character.TYPE);
		wrapper2PrimitiveTypeMap.put(Double.class, Double.TYPE);
		wrapper2PrimitiveTypeMap.put(Float.class, Float.TYPE);
		wrapper2PrimitiveTypeMap.put(Integer.class, Integer.TYPE);
		wrapper2PrimitiveTypeMap.put(Long.class, Long.TYPE);
		wrapper2PrimitiveTypeMap.put(Short.class, Short.TYPE);
		wrapper2PrimitiveTypeMap.put(Void.class, Void.TYPE);

		primitive2WrapperTypeMap.put(Boolean.TYPE, Boolean.class);
		primitive2WrapperTypeMap.put(Byte.TYPE, Byte.class);
		primitive2WrapperTypeMap.put(Character.TYPE, Character.class);
		primitive2WrapperTypeMap.put(Double.TYPE, Double.class);
		primitive2WrapperTypeMap.put(Float.TYPE, Float.class);
		primitive2WrapperTypeMap.put(Integer.TYPE, Integer.class);
		primitive2WrapperTypeMap.put(Long.TYPE, Long.class);
		primitive2WrapperTypeMap.put(Short.TYPE, Short.class);
		primitive2WrapperTypeMap.put(Void.TYPE, Void.class);
		
		primitiveTypeNameMap.put(Boolean.TYPE, "boolean");
		primitiveTypeNameMap.put(Byte.TYPE, "byte");
		primitiveTypeNameMap.put(Character.TYPE, "char");
		primitiveTypeNameMap.put(Double.TYPE, "double");
		primitiveTypeNameMap.put(Float.TYPE, "float");
		primitiveTypeNameMap.put(Integer.TYPE, "int");
		primitiveTypeNameMap.put(Long.TYPE, "long");
		primitiveTypeNameMap.put(Short.TYPE, "short");
		primitiveTypeNameMap.put(Void.TYPE, "void");

		primitiveWrapNameMap.put(Boolean.TYPE, Boolean.class.getName());
		primitiveWrapNameMap.put(Byte.TYPE, Byte.class.getName());
		primitiveWrapNameMap.put(Character.TYPE, Character.class.getName());
		primitiveWrapNameMap.put(Double.TYPE, Double.class.getName());
		primitiveWrapNameMap.put(Float.TYPE, Float.class.getName());
		primitiveWrapNameMap.put(Integer.TYPE, Integer.class.getName());
		primitiveWrapNameMap.put(Long.TYPE, Long.class.getName());
		primitiveWrapNameMap.put(Short.TYPE, Short.class.getName());
		primitiveWrapNameMap.put(Void.TYPE, Void.class.getName());
	}

	/**
	 * @return the class loader
	 */
	public static ClassLoader getClassLoader() {
		ClassLoader cl = null;

		try {
			cl = Thread.currentThread().getContextClassLoader();
		}
		catch (Throwable ex) {
			// Cannot access thread context ClassLoader - falling back to system class loader...
		}
		if (cl == null) {
			cl = ClassUtils.class.getClassLoader();
			if (cl == null) {
				cl = ClassLoader.getSystemClassLoader();
			}
		}

		return cl;
	}

	/**
	 * new instance by the className
	 * @param className class name
	 * @return object instance
	 * @throws ClassNotFoundException if class not found
	 * @throws InstantiationException if InstantiationException occurs 
	 * @throws IllegalAccessException if IllegalAccessException occurs 
	 */
	public static Object newInstance(String className) throws ClassNotFoundException,
			InstantiationException, IllegalAccessException {
		return newInstance(getClass(className));
	}

	/**
	 * new instance by the className 
	 * @param className class name
	 * @param argValue constructor argument value
	 * @param argType constructor argument type
	 * @return class instance
	 * @throws ClassNotFoundException if ClassNotFoundException occurs
	 * @throws InstantiationException if InstantiationException occurs 
	 * @throws IllegalAccessException if IllegalAccessException occurs
	 * @throws InvocationTargetException if InvocationTargetException occurs
	 */
	public static Object newInstance(String className, Object argValue, Class<?> argType)
			throws InstantiationException, IllegalAccessException, InvocationTargetException,
			ClassNotFoundException {
		return newInstance(getClass(className), new Object[] { argValue }, new Class<?>[] { argType });
	}

	/**
	 * new instance by the className
	 * @param className class name
	 * @return object instance
	 * @param argValues constructor arguments value
	 * @param argTypes constructor arguments type
	 * @throws ClassNotFoundException if class not found
	 * @throws InstantiationException if InstantiationException occurs 
	 * @throws IllegalAccessException if IllegalAccessException occurs 
	 * @throws InvocationTargetException if InvocationTargetException occurs
	 */
	public static Object newInstance(String className, Object[] argValues, Class<?>[] argTypes)
			throws InstantiationException, IllegalAccessException, InvocationTargetException,
			ClassNotFoundException {
		return newInstance(getClass(className), argValues, argTypes);
	}

	/**
	 * new instance by the clazz 
	 * @param clazz class
	 * @return object instance
	 * @throws InstantiationException if InstantiationException occurs 
	 * @throws IllegalAccessException if IllegalAccessException occurs 
	 */
	public static Object newInstance(Class<?> clazz) throws InstantiationException, IllegalAccessException {
		return clazz.newInstance();
	}

	/**
	 * new instance by the clazz 
	 * @param clazz class
	 * @param argValue constructor argument value
	 * @param argType constructor argument type
	 * @return class instance
	 * @throws InstantiationException if InstantiationException occurs 
	 * @throws IllegalAccessException if IllegalAccessException occurs 
	 * @throws InvocationTargetException if InvocationTargetException occurs
	 */
	public static Object newInstance(Class<?> clazz, Object argValue, Class<?> argType)
		throws InstantiationException, IllegalAccessException, InvocationTargetException {
		return newInstance(clazz, new Object[] { argValue }, new Class<?>[] { argType });
	}

	/**
	 * new instance by the clazz
	 * @param clazz class
	 * @return object instance
	 * @param argValues constructor arguments value
	 * @param argTypes constructor arguments type
	 * @throws InstantiationException if InstantiationException occurs 
	 * @throws IllegalAccessException if IllegalAccessException occurs 
	 * @throws InvocationTargetException if InvocationTargetException occurs
	 * @see ConstructorUtils#invokeConstructor(Class<?>, Class<?>[], Object[])
	 */
	public static Object newInstance(Class<?> clazz, Object[] argValues, Class<?>[] argTypes)
		throws InstantiationException, IllegalAccessException, InvocationTargetException {
		return ConstructorUtils.invokeConstructor(clazz, argTypes, argValues);
	}

	/**
	 * Returns a {@link Constructor} for the given method signature, or <tt>null</tt>
	 * if no such <tt>Constructor</tt> can be found.
	 *
	 * @param type     the (non-<tt>null</tt>) type of {@link Object} the returned {@link Constructor} should create
	 * @param argTypes a non-<tt>null</tt> array of types describing the parameters to the {@link Constructor}.
	 * @return a {@link Constructor} for the given method signature, or <tt>null</tt>
	 *         if no such <tt>Constructor</tt> can be found.
	 * @see ConstructorUtils#getConstructor(Class<?>, Class<?>[])
	 */
	public static Constructor getConstructor(Class<?> type, Class<?>[] argTypes) {
		return ConstructorUtils.getConstructor(type, argTypes);
	}
	
	/**
	 * Override the thread context ClassLoader with the environment's bean ClassLoader
	 * if necessary, i.e. if the bean ClassLoader is not equivalent to the thread
	 * context ClassLoader already.
	 * @param classLoaderToUse the actual ClassLoader to use for the thread context
	 * @return the original thread context ClassLoader, or <code>null</code> if not overridden
	 */
	public static ClassLoader overrideThreadContextClassLoader(ClassLoader classLoaderToUse) {
		Thread currentThread = Thread.currentThread();
		ClassLoader threadContextClassLoader = currentThread.getContextClassLoader();
		if (classLoaderToUse != null && !classLoaderToUse.equals(threadContextClassLoader)) {
			currentThread.setContextClassLoader(classLoaderToUse);
			return threadContextClassLoader;
		}
		else {
			return null;
		}
	}

	/**
	 * Determine whether the {@link Class} identified by the supplied name is present
	 * and can be loaded. Will return <code>false</code> if either the class or
	 * one of its dependencies is not present or cannot be loaded.
	 * @param className the name of the class to check
	 * @return whether the specified class is present
	 */
	public static boolean isPresent(String className) {
		return isPresent(className, getClassLoader());
	}

	/**
	 * Determine whether the {@link Class} identified by the supplied name is present
	 * and can be loaded. Will return <code>false</code> if either the class or
	 * one of its dependencies is not present or cannot be loaded.
	 * @param className the name of the class to check
	 * @param classLoader the class loader to use
	 * (may be <code>null</code>, which indicates the default class loader)
	 * @return whether the specified class is present
	 */
	public static boolean isPresent(String className, ClassLoader classLoader) {
		try {
			getClass(classLoader, className);
			return true;
		}
		catch (Throwable ex) {
			// Class or one of its dependencies is not present...
			return false;
		}
	}

	/**
	 * Primitive Class to Wrapper Class: int.class -> Integer.class
	 * @param type the type of the potentially primitive class
	 * @return the primitive wrapper class
	 */
	public static Class<?> primitive2Wrapper(Class<?> type) {
		if (type != null && type.isPrimitive()) {
			type = primitive2WrapperTypeMap.get(type);
		}
		return type;
	}
	
	/**
	 * Wrapper Class to Primitive Class: Integer.class -> int.class
	 * @param type the type of the potentially primitive wrapper class
	 * @return the primitive class
	 */
	public static Class<?> wrapper2Primitive(Class<?> type) {
		Class<?> wrapper = wrapper2PrimitiveTypeMap.get(type);
		return (wrapper == null ? type : wrapper);
	}
	
	/**
	 * get primitive type name: int.class -> "int"
	 * @param type the type of the potentially primitive class
	 * @return primitive type name
	 */
	public static String getPrimitiveTypeName(Class<?> type) {
		if (type == null) {
			return null;
		}

		if (type.isPrimitive()) {
			return primitiveTypeNameMap.get(type);
		}
		else {
			return type.getName();
		}
	}
	
	/**
	 * get primitive wrapper class name: int.class -> "java.lang.Integer"
	 * @param type the type of the potentially primitive class
	 * @return primitive wrapper class name
	 */
	public static String getPrimitiveWrapName(Class<?> type) {
		if (type == null) {
			return null;
		}

		if (type.isPrimitive()) {
			return primitiveWrapNameMap.get(type);
		}
		else {
			return type.getName();
		}
	}

	/**
	 * Return the user-defined class for the given instance: usually simply
	 * the class of the given instance, but the original class in case of a
	 * CGLIB-generated subclass.
	 * @param instance the instance to check
	 * @return the user-defined class
	 */
	public static Class<?> getUserClass(Object instance) {
		Assert.notNull(instance, "Instance must not be null");
		return getUserClass(instance.getClass());
	}

	/**
	 * Return the user-defined class for the given class: usually simply the given
	 * class, but the original class in case of a CGLIB-generated subclass.
	 * @param clazz the class to check
	 * @return the user-defined class
	 */
	public static Class<?> getUserClass(Class<?> clazz) {
		return (clazz != null && clazz.getName().indexOf(CGLIB_CLASS_SEPARATOR) != -1 ?
				clazz.getSuperclass() : clazz);
	}

	/**
	 * Check whether the given class is cache-safe in the given context,
	 * i.e. whether it is loaded by the given ClassLoader or a parent of it.
	 * @param clazz the class to analyze
	 * @param classLoader the ClassLoader to potentially cache metadata in
	 * @return true if the given class is cache-safe
	 */
	public static boolean isCacheSafe(Class<?> clazz, ClassLoader classLoader) {
		Assert.notNull(clazz, "Class must not be null");
		ClassLoader target = clazz.getClassLoader();
		if (target == null) {
			return false;
		}
		ClassLoader cur = classLoader;
		if (cur == target) {
			return true;
		}
		while (cur != null) {
			cur = cur.getParent();
			if (cur == target) {
				return true;
			}
		}
		return false;
	}


    // ----------------------------------------------------------------------
    /**
     * <p>Gets the class name minus the package name for an <code>Object</code>.</p>
     *
     * @param object  the class to get the short name for, may be null
     * @param valueIfNull  the value to return if null
     * @return the class name of the object without the package name, or the null value
     */
    public static String getSimpleClassName(Object object, String valueIfNull) {
        if (object == null) {
            return valueIfNull;
        }
        return getSimpleClassName(object.getClass().getName());
    }
    
	/**
	 * Get the class name without the qualified package name.
	 * @param className the className to get the short name for
	 * @return the class name of the class without the package name
	 * @throws IllegalArgumentException if the className is empty
	 */
	public static String getSimpleClassName(String className) {
		return getShortClassName(className);
	}

	/**
	 * Get the class name without the qualified package name.
	 * @param clazz the class to get the short name for
	 * @return the class name of the class without the package name
	 */
	public static String getSimpleClassName(Class<?> clazz) {
		return getSimpleClassName(getQualifiedClassName(clazz));
	}

	/**
	 * Determine the name of the class file, relative to the containing
	 * package: e.g. "String.class"
	 * @param clazz the class
	 * @return the file name of the ".class" file
	 */
	public static String getClassFileName(Class<?> clazz) {
		Assert.notNull(clazz, "Class must not be null");
		String className = clazz.getName();
		int lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
		return className.substring(lastDotIndex + 1) + CLASS_FILE_SUFFIX;
	}

	/**
	 * Return the qualified name of the given class: usually simply
	 * the class name, but component type class name + "[]" for arrays.
	 * @param clazz the class
	 * @return the qualified name of the class
	 */
	public static String getQualifiedClassName(Class<?> clazz) {
		Assert.notNull(clazz, "Class must not be null");
		if (clazz.isArray()) {
			StringBuilder sb = new StringBuilder();
			while (clazz.isArray()) {
				clazz = clazz.getComponentType();
				sb.append(ClassUtils.ARRAY_SUFFIX);
			}
			sb.insert(0, getQualifiedClassName(clazz));
			return sb.toString();
		}
		else if (clazz.isPrimitive()) {
			return getPrimitiveTypeName(clazz);
		}
		else {
			return clazz.getName();
		}
	}

	/**
	 * Return the castable class name of the given class, usually wrap
	 * the class name: "int" -> "Integer".
	 * @param clazz the class
	 * @return the castable class name
	 */
	public static String getCastableClassName(Class<?> clazz) {
		if (clazz.isArray()) {
			StringBuilder sb = new StringBuilder();
			while (clazz.isArray()) {
				clazz = clazz.getComponentType();
				sb.append("[]");
			}
			sb.insert(0, getQualifiedClassName(clazz));
			return sb.toString();
		}
		else if (clazz.isPrimitive()) {
			return getPrimitiveWrapName(clazz);
		}
		else {
			return clazz.getName();
		}
	}

	/**
	 * Return the qualified name of the given method, consisting of
	 * fully qualified interface/class name + "." + method name.
	 * @param method the method
	 * @return the qualified name of the method
	 */
	public static String getQualifiedMethodName(Method method) {
		Assert.notNull(method, "Method must not be null");
		return method.getDeclaringClass().getName() + "." + method.getName();
	}

	/**
	 * Return a descriptive name for the given object's type: usually simply
	 * the class name, but component type class name + "[]" for arrays,
	 * and an appended list of implemented interfaces for JDK proxies.
	 * @param value the value to introspect
	 * @return the qualified name of the class
	 */
	public static String getDescriptiveType(Object value) {
		if (value == null) {
			return null;
		}
		Class<?> clazz = value.getClass();
		if (Proxy.isProxyClass(clazz)) {
			StringBuilder buf = new StringBuilder(clazz.getName());
			buf.append(" implementing ");
			Class<?>[] ifcs = clazz.getInterfaces();
			for (int i = 0; i < ifcs.length; i++) {
				buf.append(ifcs[i].getName());
				if (i < ifcs.length - 1) {
					buf.append(',');
				}
			}
			return buf.toString();
		}
		else {
			return getQualifiedClassName(clazz);
		}
	}


	/**
	 * Determine whether the given class has a constructor with the given signature.
	 * <p>Essentially translates <code>NoSuchMethodException</code> to "false".
	 * @param clazz	the clazz to analyze
	 * @param paramTypes the parameter types of the method
	 * @return whether the class has a corresponding constructor
	 * @see java.lang.Class#getMethod
	 */
	public static boolean hasConstructor(Class<?> clazz, Class<?>[] paramTypes) {
		return (getConstructorIfAvailable(clazz, paramTypes) != null);
	}

	/**
	 * Determine whether the given class has a constructor with the given signature,
	 * and return it if available (else return <code>null</code>).
	 * <p>Essentially translates <code>NoSuchMethodException</code> to <code>null</code>.
	 * @param clazz	the clazz to analyze
	 * @param paramTypes the parameter types of the method
	 * @return the constructor, or <code>null</code> if not found
	 * @see java.lang.Class#getConstructor
	 */
	public static Constructor getConstructorIfAvailable(Class<?> clazz, Class<?>[] paramTypes) {
		Assert.notNull(clazz, "Class must not be null");
		try {
			return clazz.getConstructor(paramTypes);
		}
		catch (NoSuchMethodException ex) {
			return null;
		}
	}

	/**
	 * Determine whether the given class has a method with the given signature.
	 * <p>Essentially translates <code>NoSuchMethodException</code> to "false".
	 * @param clazz	the clazz to analyze
	 * @param methodName the name of the method
	 * @param paramTypes the parameter types of the method
	 * @return whether the class has a corresponding method
	 * @see java.lang.Class#getMethod
	 */
	public static boolean hasMethod(Class<?> clazz, String methodName, Class<?>[] paramTypes) {
		return (getMethodIfAvailable(clazz, methodName, paramTypes) != null);
	}

	/**
	 * Determine whether the given class has a method with the given signature,
	 * and return it if available (else return <code>null</code>).
	 * <p>Essentially translates <code>NoSuchMethodException</code> to <code>null</code>.
	 * @param clazz	the clazz to analyze
	 * @param methodName the name of the method
	 * @param paramTypes the parameter types of the method
	 * @return the method, or <code>null</code> if not found
	 * @see java.lang.Class#getMethod
	 */
	public static Method getMethodIfAvailable(Class<?> clazz, String methodName, Class<?>[] paramTypes) {
		Assert.notNull(clazz, "Class must not be null");
		Assert.notNull(methodName, "Method name must not be null");
		try {
			return clazz.getMethod(methodName, paramTypes);
		}
		catch (NoSuchMethodException ex) {
			return null;
		}
	}

	/**
	 * Return the number of methods with a given name (with any argument types),
	 * for the given class and/or its superclasses. Includes non-public methods.
	 * @param clazz	the clazz to check
	 * @param methodName the name of the method
	 * @return the number of methods with the given name
	 */
	public static int getMethodCountForName(Class<?> clazz, String methodName) {
		Assert.notNull(clazz, "Class must not be null");
		Assert.notNull(methodName, "Method name must not be null");
		int count = 0;
		Method[] declaredMethods = clazz.getDeclaredMethods();
		for (int i = 0; i < declaredMethods.length; i++) {
			Method method = declaredMethods[i];
			if (methodName.equals(method.getName())) {
				count++;
			}
		}
		Class<?>[] ifcs = clazz.getInterfaces();
		for (int i = 0; i < ifcs.length; i++) {
			count += getMethodCountForName(ifcs[i], methodName);
		}
		if (clazz.getSuperclass() != null) {
			count += getMethodCountForName(clazz.getSuperclass(), methodName);
		}
		return count;
	}

	/**
	 * Does the given class and/or its superclasses at least have one or more
	 * methods (with any argument types)? Includes non-public methods.
	 * @param clazz	the clazz to check
	 * @param methodName the name of the method
	 * @return whether there is at least one method with the given name
	 */
	public static boolean hasAtLeastOneMethodWithName(Class<?> clazz, String methodName) {
		Assert.notNull(clazz, "Class must not be null");
		Assert.notNull(methodName, "Method name must not be null");
		Method[] declaredMethods = clazz.getDeclaredMethods();
		for (int i = 0; i < declaredMethods.length; i++) {
			Method method = declaredMethods[i];
			if (method.getName().equals(methodName)) {
				return true;
			}
		}
		Class<?>[] ifcs = clazz.getInterfaces();
		for (int i = 0; i < ifcs.length; i++) {
			if (hasAtLeastOneMethodWithName(ifcs[i], methodName)) {
				return true;
			}
		}
		return (clazz.getSuperclass() != null && hasAtLeastOneMethodWithName(clazz.getSuperclass(), methodName));
	}

	/**
	 * Return a static method of a class.
	 * @param methodName the static method name
	 * @param clazz	the class which defines the method
	 * @param args the parameter types to the method
	 * @return the static method, or <code>null</code> if no static method was found
	 * @throws IllegalArgumentException if the method name is blank or the clazz is null
	 */
	public static Method getStaticMethod(Class<?> clazz, String methodName, Class<?>[] args) {
		Assert.notNull(clazz, "Class must not be null");
		Assert.notNull(methodName, "Method name must not be null");
		try {
			Method method = clazz.getDeclaredMethod(methodName, args);
			if ((method.getModifiers() & Modifier.STATIC) != 0) {
				return method;
			}
		}
		catch (NoSuchMethodException ex) {
		}
		return null;
	}


	/**
	 * Check if the given class represents a primitive wrapper,
	 * i.e. Boolean, Byte, Character, Short, Integer, Long, Float, or Double.
	 * @param clazz the class to check
	 * @return whether the given class is a primitive wrapper class
	 */
	public static boolean isPrimitiveWrapper(Class<?> clazz) {
		Assert.notNull(clazz, "Class must not be null");
		return wrapper2PrimitiveTypeMap.containsKey(clazz);
	}

	/**
	 * Check if the given class represents a primitive (i.e. boolean, byte,
	 * char, short, int, long, float, or double) or a primitive wrapper
	 * (i.e. Boolean, Byte, Character, Short, Integer, Long, Float, or Double).
	 * @param clazz the class to check
	 * @return whether the given class is a primitive or primitive wrapper class
	 */
	public static boolean isPrimitiveOrWrapper(Class<?> clazz) {
		Assert.notNull(clazz, "Class must not be null");
		return (clazz.isPrimitive() || isPrimitiveWrapper(clazz));
	}

	/**
	 * Check if the given class represents an array of primitives,
	 * i.e. boolean, byte, char, short, int, long, float, or double.
	 * @param clazz the class to check
	 * @return whether the given class is a primitive array class
	 */
	public static boolean isPrimitiveArray(Class<?> clazz) {
		Assert.notNull(clazz, "Class must not be null");
		return (clazz.isArray() && clazz.getComponentType().isPrimitive());
	}

	/**
	 * Check if the given class represents an array of primitive wrappers,
	 * i.e. Boolean, Byte, Character, Short, Integer, Long, Float, or Double.
	 * @param clazz the class to check
	 * @return whether the given class is a primitive wrapper array class
	 */
	public static boolean isPrimitiveWrapperArray(Class<?> clazz) {
		Assert.notNull(clazz, "Class must not be null");
		return (clazz.isArray() && isPrimitiveWrapper(clazz.getComponentType()));
	}

	/**
	 * Check if the right-hand side type may be assigned to the left-hand side
	 * type, assuming setting by reflection. Considers primitive wrapper
	 * classes as assignable to the corresponding primitive types.
	 * @param lhsType the target type
	 * @param rhsType	the value type that should be assigned to the target type
	 * @return if the target type is assignable from the value type
	 */
	public static boolean isAssignable(Class<?> lhsType, Class<?> rhsType) {
		Assert.notNull(lhsType, "Left-hand side type must not be null");
		Assert.notNull(rhsType, "Right-hand side type must not be null");
		return (lhsType.isAssignableFrom(rhsType) ||
				lhsType.equals(wrapper2PrimitiveTypeMap.get(rhsType)));
	}

	/**
	 * Determine if the given type is assignable from the given value,
	 * assuming setting by reflection. Considers primitive wrapper classes
	 * as assignable to the corresponding primitive types.
	 * @param type	the target type
	 * @param value the value that should be assigned to the type
	 * @return if the type is assignable from the value
	 */
	public static boolean isAssignableValue(Class<?> type, Object value) {
		Assert.notNull(type, "Type must not be null");
		return (value != null ? isAssignable(type, value.getClass()) : !type.isPrimitive());
	}


	/**
	 * Convert a "/"-based resource path to a "."-based fully qualified class name.
	 * @param resourcePath the resource path pointing to a class
	 * @return the corresponding fully qualified class name
	 */
	public static String resourcePathToClassName(String resourcePath) {
		return resourcePath.replace('/', '.');
	}

	/**
	 * Convert a "."-based fully qualified class name to a "/"-based resource path.
	 * @param className the fully qualified class name
	 * @return the corresponding resource path, pointing to the class
	 */
	public static String classNameToResourcePath(String className) {
		return className.replace('.', '/');
	}

	/**
	 * Return a path suitable for use with <code>ClassLoader.getResource</code>
	 * (also suitable for use with <code>Class.getResource</code> by prepending a
	 * slash ('/') to the return value. Built by taking the package of the specified
	 * class file, converting all dots ('.') to slashes ('/'), adding a trailing slash
	 * if necesssary, and concatenating the specified resource name to this.
	 * <br/>As such, this function may be used to build a path suitable for
	 * loading a resource file that is in the same package as a class file.
	 * @param clazz	the Class whose package will be used as the base
	 * @param resourceName the resource name to append. A leading slash is optional.
	 * @return the built-up resource path
	 * @see java.lang.ClassLoader#getResource
	 * @see java.lang.Class#getResource
	 */
	public static String getResourcePath(Class<?> clazz, String resourceName) {
		Assert.notNull(resourceName, "Resource name must not be null");
		if (!resourceName.startsWith("/")) {
			return classPackageAsResourcePath(clazz) + "/" + resourceName;
		}
		return classPackageAsResourcePath(clazz) + resourceName;
	}

	/**
	 * Given an input class object, return a string which consists of the
	 * class's package name as a pathname, i.e., all dots ('.') are replaced by
	 * slashes ('/'). Neither a leading nor trailing slash is added. The result
	 * could be concatenated with a slash and the name of a resource, and fed
	 * directly to <code>ClassLoader.getResource()</code>. For it to be fed to
	 * <code>Class.getResource</code> instead, a leading slash would also have
	 * to be prepended to the returned value.
	 * @param clazz the input class. A <code>null</code> value or the default
	 * (empty) package will result in an empty string ("") being returned.
	 * @return a path which represents the package name
	 * @see ClassLoader#getResource
	 * @see Class#getResource
	 */
	public static String classPackageAsResourcePath(Class<?> clazz) {
		if (clazz == null) {
			return "";
		}
		String className = clazz.getName();
		int packageEndIndex = className.lastIndexOf('.');
		if (packageEndIndex == -1) {
			return "";
		}
		String packageName = className.substring(0, packageEndIndex);
		return packageName.replace('.', '/');
	}

	/**
	 * Build a String that consists of the names of the classes/interfaces
	 * in the given array.
	 * <p>Basically like <code>AbstractCollection.toString()</code>, but stripping
	 * the "class "/"interface " prefix before every class name.
	 * @param classes a Collection of Class objects (may be <code>null</code>)
	 * @return a String of form "[com.foo.Bar, com.foo.Baz]"
	 * @see java.util.AbstractCollection#toString()
	 */
	public static String classNamesToString(Class<?>[] classes) {
		return classNamesToString(Arrays.asList(classes));
	}

	/**
	 * Build a String that consists of the names of the classes/interfaces
	 * in the given collection.
	 * <p>Basically like <code>AbstractCollection.toString()</code>, but stripping
	 * the "class "/"interface " prefix before every class name.
	 * @param classes a Collection of Class objects (may be <code>null</code>)
	 * @return a String of form "[com.foo.Bar, com.foo.Baz]"
	 * @see java.util.AbstractCollection#toString()
	 */
	public static String classNamesToString(Collection classes) {
		if (CollectionUtils.isEmpty(classes)) {
			return "[]";
		}
		StringBuilder sb = new StringBuilder("[");
		for (Iterator it = classes.iterator(); it.hasNext(); ) {
			Class<?> clazz = (Class<?>) it.next();
			sb.append(clazz.getName());
			if (it.hasNext()) {
				sb.append(", ");
			}
		}
		sb.append("]");
		return sb.toString();
	}


	/**
	 * Return all interfaces that the given instance implements as array,
	 * including ones implemented by superclasses.
	 * @param instance the instance to analyse for interfaces
	 * @return all interfaces that the given instance implements as array
	 */
	public static Class<?>[] getAllInterfaces(Object instance) {
		Assert.notNull(instance, "Instance must not be null");
		return getAllInterfacesForClass(instance.getClass());
	}

	/**
	 * Return all interfaces that the given class implements as array,
	 * including ones implemented by superclasses.
	 * <p>If the class itself is an interface, it gets returned as sole interface.
	 * @param clazz the class to analyse for interfaces
	 * @return all interfaces that the given object implements as array
	 */
	public static Class<?>[] getAllInterfacesForClass(Class<?> clazz) {
		return getAllInterfacesForClass(clazz, null);
	}

	/**
	 * Return all interfaces that the given class implements as array,
	 * including ones implemented by superclasses.
	 * <p>If the class itself is an interface, it gets returned as sole interface.
	 * @param clazz the class to analyse for interfaces
	 * @param classLoader the ClassLoader that the interfaces need to be visible in
	 * (may be <code>null</code> when accepting all declared interfaces)
	 * @return all interfaces that the given object implements as array
	 */
	public static Class<?>[] getAllInterfacesForClass(Class<?> clazz, ClassLoader classLoader) {
		Assert.notNull(clazz, "Class must not be null");
		if (clazz.isInterface()) {
			return new Class<?>[] {clazz};
		}
		List<Class<?>> interfaces = new ArrayList<Class<?>>();
		while (clazz != null) {
			for (int i = 0; i < clazz.getInterfaces().length; i++) {
				Class<?> ifc = clazz.getInterfaces()[i];
				if (!interfaces.contains(ifc) &&
						(classLoader == null || isVisible(ifc, classLoader))) {
					interfaces.add(ifc);
				}
			}
			clazz = clazz.getSuperclass();
		}
		return (Class<?>[]) interfaces.toArray(new Class<?>[interfaces.size()]);
	}

	/**
	 * Return all interfaces that the given instance implements as Set,
	 * including ones implemented by superclasses.
	 * @param instance the instance to analyse for interfaces
	 * @return all interfaces that the given instance implements as Set
	 */
	public static Set getAllInterfacesAsSet(Object instance) {
		Assert.notNull(instance, "Instance must not be null");
		return getAllInterfacesForClassAsSet(instance.getClass());
	}

	/**
	 * Return all interfaces that the given class implements as Set,
	 * including ones implemented by superclasses.
	 * <p>If the class itself is an interface, it gets returned as sole interface.
	 * @param clazz the class to analyse for interfaces
	 * @return all interfaces that the given object implements as Set
	 */
	public static Set getAllInterfacesForClassAsSet(Class<?> clazz) {
		return getAllInterfacesForClassAsSet(clazz, null);
	}

	/**
	 * Return all interfaces that the given class implements as Set,
	 * including ones implemented by superclasses.
	 * <p>If the class itself is an interface, it gets returned as sole interface.
	 * @param clazz the class to analyse for interfaces
	 * @param classLoader the ClassLoader that the interfaces need to be visible in
	 * (may be <code>null</code> when accepting all declared interfaces)
	 * @return all interfaces that the given object implements as Set
	 */
	public static Set getAllInterfacesForClassAsSet(Class<?> clazz, ClassLoader classLoader) {
		Assert.notNull(clazz, "Class must not be null");
		if (clazz.isInterface()) {
			return Collections.singleton(clazz);
		}
		Set<Class<?>> interfaces = new LinkedHashSet<Class<?>>();
		while (clazz != null) {
			for (int i = 0; i < clazz.getInterfaces().length; i++) {
				Class<?> ifc = clazz.getInterfaces()[i];
				if (classLoader == null || isVisible(ifc, classLoader)) {
					interfaces.add(ifc);
				}
			}
			clazz = clazz.getSuperclass();
		}
		return interfaces;
	}

	/**
	 * Create a composite interface Class for the given interfaces,
	 * implementing the given interfaces in one single Class.
	 * <p>This implementation builds a JDK proxy class for the given interfaces.
	 * @param interfaces the interfaces to merge
	 * @param classLoader the ClassLoader to create the composite Class in
	 * @return the merged interface as Class
	 * @see java.lang.reflect.Proxy#getProxyClass
	 */
	public static Class<?> createCompositeInterface(Class[] interfaces, ClassLoader classLoader) {
		Assert.notEmpty(interfaces, "Interfaces must not be empty");
		Assert.notNull(classLoader, "ClassLoader must not be null");
		return Proxy.getProxyClass(classLoader, interfaces);
	}

	/**
	 * Check whether the given class is visible in the given ClassLoader.
	 * @param clazz the class to check (typically an interface)
	 * @param classLoader the ClassLoader to check against (may be <code>null</code>,
	 * in which case this method will always return <code>true</code>)
	 * @return true if the given class is visible
	 */
	public static boolean isVisible(Class<?> clazz, ClassLoader classLoader) {
		if (classLoader == null) {
			return true;
		}
		try {
			Class<?> actualClass = classLoader.loadClass(clazz.getName());
			return (clazz == actualClass);
			// Else: different interface class found...
		}
		catch (ClassNotFoundException ex) {
			// No interface class found...
			return false;
		}
	}

	/**
	 * Get the underlying class for a type, or null if the type is a variable type.
	 * 
	 * @param type the type
	 * @return the underlying class
	 */
	public static Class<?> getClass(Type type) {
		if (type instanceof Class) {
			return (Class)type;
		}
		else if (type instanceof ParameterizedType) {
			return getClass(((ParameterizedType)type).getRawType());
		}
		else if (type instanceof GenericArrayType) {
			Type componentType = ((GenericArrayType)type).getGenericComponentType();
			Class<?> componentClass = getClass(componentType);
			if (componentClass != null) {
				return Array.newInstance(componentClass, 0).getClass();
			}
			else {
				return null;
			}
		}
		else {
			return null;
		}
	}

	/**
	 * <pre>
	 *   class Test {
	 *     List<String> list ;
	 *     
	 *     void test() {
	 *       // return "java.lang.String";
	 *       ClassUtils.getGenericFiedElementClass(Test.class, "list");
	 *     }
	 *   }
	 * </pre>
	 * @param clazz  class
	 * @param fieldName field name
	 * @return element class
	 * @throws SecurityException
	 * @throws NoSuchFieldException
	 */
	public static Class<?> getGenericFieldElementClass(Class clazz, String fieldName)
			throws SecurityException, NoSuchFieldException {
		Field field = clazz.getDeclaredField(fieldName);
		Type type = field.getGenericType();
		if (type instanceof ParameterizedType) {
			Type[] argTypes = ((ParameterizedType)type).getActualTypeArguments();
			if (ArrayUtils.isNotEmpty(argTypes)) {
				return getClass(argTypes[0]);
			}
		}
		return null;
	}

}
