/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2002-2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowledgement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgement may appear in the software itself,
* if and wherever such third-party acknowledgements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
*
Operates on classes without using reflection.
* *This class handles invalid null
inputs as best it can.
* Each method documents its behaviour in more detail.
The package separator character: .
.
The package separator String: .
.
The inner class separator character: $
.
The inner class separator String: $
.
ClassUtils instances should NOT be constructed in standard programming.
* Instead, the class should be used as
* ClassUtils.getShortClassName(cls)
.
This constructor is public to permit tools that require a JavaBean * instance to operate.
*/ public ClassUtils() { } // Short class name // ---------------------------------------------------------------------- /** *Gets the class name minus the package name for an Object
.
Gets the class name minus the package name from a Class
.
null
* @return the class name without the package name
* @throws IllegalArgumentException if the class is null
*/
public static String getShortClassName(Class cls) {
if (cls == null) {
throw new IllegalArgumentException("The class must not be null");
}
return getShortClassName(cls.getName());
}
/**
* Gets the class name minus the package name from a String.
* *The string passed in is assumed to be a class name - it is not checked.
* * @param className the className to get the short name for, * must not be empty ornull
* @return the class name of the class without the package name
* @throws IllegalArgumentException if the className is empty
*/
public static String getShortClassName(String className) {
if (StringUtils.isEmpty(className)) {
throw new IllegalArgumentException("The class name must not be empty");
}
char[] chars = className.toCharArray();
int lastDot = 0;
for (int i = 0; i < chars.length; i++) {
if (chars[i] == PACKAGE_SEPARATOR_CHAR) {
lastDot = i + 1;
} else if (chars[i] == INNER_CLASS_SEPARATOR_CHAR) { // handle inner classes
chars[i] = PACKAGE_SEPARATOR_CHAR;
}
}
return new String(chars, lastDot, chars.length - lastDot);
}
// Package name
// ----------------------------------------------------------------------
/**
* Gets the package name of an Object
.
Gets the package name of a Class
.
null
* @return the package name
* @throws IllegalArgumentException if the class is null
*/
public static String getPackageName(Class cls) {
if (cls == null) {
throw new IllegalArgumentException("The class must not be null");
}
return getPackageName(cls.getName());
}
/**
* Gets the package name from a String
.
The string passed in is assumed to be a class name - it is not checked.
* * @param className the className to get the package name for, * must not be empty ornull
* @return the package name
* @throws IllegalArgumentException if the className is empty
*/
public static String getPackageName(String className) {
if (StringUtils.isEmpty(className)) {
throw new IllegalArgumentException("The class name must not be empty");
}
int i = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
if (i == -1) {
return "";
}
return className.substring(0, i);
}
// Superclasses/Superinterfaces
// ----------------------------------------------------------------------
/**
* Gets a List
of superclasses for the given class.
null
* @return the List
of superclasses in order going up from this one
* null
if null input
*/
public static List getAllSuperclasses(Class cls) {
if (cls == null) {
return null;
}
List classes = new ArrayList();
Class superclass = cls.getSuperclass();
while (superclass != null) {
classes.add(superclass);
superclass = superclass.getSuperclass();
}
return classes;
}
/**
* Gets a List
of all interfaces implemented by the given
* class and its superclasses.
The order is determined by looking through each interface in turn as * declared in the source file and following its hieracrchy up. Then each * superclass is considered in the same way. Later duplicates are ignored, * so the order is maintained.
* * @param cls the class to look up, must not benull
* @return the List
of interfaces in order,
* null
if null input
*/
public static List getAllInterfaces(Class cls) {
if (cls == null) {
return null;
}
List list = new ArrayList();
while (cls != null) {
Class[] interfaces = cls.getInterfaces();
for (int i = 0; i < interfaces.length; i++) {
if (list.contains(interfaces[i]) == false) {
list.add(interfaces[i]);
}
List superInterfaces = getAllInterfaces(interfaces[i]);
for (Iterator it = superInterfaces.iterator(); it.hasNext();) {
Class intface = (Class) it.next();
if (list.contains(intface) == false) {
list.add(intface);
}
}
}
cls = cls.getSuperclass();
}
return list;
}
// /**
// * Gets a List
of subclasses of the specified class.
This method searches the classpath to find all the subclasses // * of a particular class available. No classes are loaded, the // * returned list contains class names, not classes.
// * // * @param cls the class to find subclasses for // * @return theList
of subclass String class names
// * @throws IllegalArgumentException if the class is null
// */
// public static List getAllSubclassNames(Class cls) {
// if (cls == null) {
// throw new IllegalArgumentException("The class must not be null");
// }
// // TODO Use JavaWorld tip for searching the classpath
// return null;
// }
// /**
// * Gets a List
of subclasses of the specified class.
This method searches the classpath to find all the subclasses // * of a particular class available.
// * // * @param cls the class to find subclasses for // * @return theList
of subclasses
// * @throws IllegalArgumentException if the class is null
// */
// public static List getAllSubclasses(Class cls) {
// List names = getAllSubclassNames(cls);
// return convertClassNamesToClasses(names);
// }
// /**
// * Gets a List
of implementations of the specified interface.
This method searches the classpath to find all the implementations // * of a particular interface available. No classes are loaded, the // * returned list contains class names, not classes.
// * // * @param cls the class to find sub classes for // * @return theList
of implementation String class names
// * @throws IllegalArgumentException if the class is null
// */
// public static List getAllImplementationClassNames(Class cls) {
// if (cls == null) {
// throw new IllegalArgumentException("The class must not be null");
// }
// // TODO Use JavaWorld tip for searching the classpath
// return null;
// }
// Convert list
// ----------------------------------------------------------------------
/**
* Given a List
of class names, this method converts them into classes.
A new List
is returned. If the class name cannot be found, null
* is stored in the List
. If the class name in the List
is
* null
, null
is stored in the output List
.
List
of Class objects corresponding to the class names,
* null
if null input
* @throws ClassCastException if classNames contains a non String entry
*/
public static List convertClassNamesToClasses(List classNames) {
if (classNames == null) {
return null;
}
List classes = new ArrayList(classNames.size());
for (Iterator it = classNames.iterator(); it.hasNext();) {
String className = (String) it.next();
try {
classes.add(Class.forName(className));
} catch (Exception ex) {
classes.add(null);
}
}
return classes;
}
/**
* Given a List
of Class
objects, this method converts
* them into class names.
A new List
is returned. null
objects will be copied into
* the returned list as null
.
List
of Class objects corresponding to the class names,
* null
if null input
* @throws ClassCastException if classNames contains a non Class or null entry
*/
public static List convertClassesToClassNames(List classes) {
if (classes == null) {
return null;
}
List classNames = new ArrayList(classes.size());
for (Iterator it = classes.iterator(); it.hasNext();) {
Class cls = (Class) it.next();
if (cls == null) {
classNames.add(null);
} else {
classNames.add(cls.getName());
}
}
return classNames;
}
// Is assignable
// ----------------------------------------------------------------------
/**
* Checks if an array of Classes can be assigned to another array of Classes.
* *This method calls {@link #isAssignable(Class, Class) isAssignable} for each * Class pair in the input arrays. It can be used to check if a set of arguments * (the first parameter) are suitably compatable with a set of method parameter types * (the second parameter).
* *Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method, this
* method takes into account widenings of primitive classes and
* null
s.
Primitive widenings allow an int to be assigned to a long
,
* float
or double
. This method returns the correct
* result for these cases.
Null
may be assigned to any reference type. This method will
* return true
if null
is passed in and the toClass is
* non-primitive.
Specifically, this method tests whether the type represented by the
* specified Class
parameter can be converted to the type
* represented by this Class
object via an identity conversion
* widening primitive or widening reference conversion. See
* The Java Language Specification,
* sections 5.1.1, 5.1.2 and 5.1.4 for details.
null
* @param toClassArray the array of Classes to try to assign into, may be null
* @return true
if assignment possible
*/
public static boolean isAssignable(Class[] classArray, Class[] toClassArray) {
if (ArrayUtils.isSameLength(classArray, toClassArray) == false) {
return false;
}
if (classArray == null) {
classArray = ArrayUtils.EMPTY_CLASS_ARRAY;
}
if (toClassArray == null) {
toClassArray = ArrayUtils.EMPTY_CLASS_ARRAY;
}
for (int i = 0; i < classArray.length; i++) {
if (isAssignable(classArray[i], toClassArray[i]) == false) {
return false;
}
}
return true;
}
/**
* Checks if one Class
can be assigned to a variable of
* another Class
.
Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method,
* this method takes into account widenings of primitive classes and
* null
s.
Primitive widenings allow an int to be assigned to a long, float or * double. This method returns the correct result for these cases.
* *Null
may be assigned to any reference type. This method
* will return true
if null
is passed in and the
* toClass is non-primitive.
Specifically, this method tests whether the type represented by the
* specified Class
parameter can be converted to the type
* represented by this Class
object via an identity conversion
* widening primitive or widening reference conversion. See
* The Java Language Specification,
* sections 5.1.1, 5.1.2 and 5.1.4 for details.
true
if assignment possible
*/
public static boolean isAssignable(Class cls, Class toClass) {
if (toClass == null) {
return false;
}
// have to check for null, as isAssignableFrom doesn't
if (cls == null) {
return !(toClass.isPrimitive());
}
if (cls.equals(toClass)) {
return true;
}
if (cls.isPrimitive()) {
if (toClass.isPrimitive() == false) {
return false;
}
if (Integer.TYPE.equals(cls)) {
return Long.TYPE.equals(toClass)
|| Float.TYPE.equals(toClass)
|| Double.TYPE.equals(toClass);
}
if (Long.TYPE.equals(cls)) {
return Float.TYPE.equals(toClass)
|| Double.TYPE.equals(toClass);
}
if (Boolean.TYPE.equals(cls)) {
return false;
}
if (Double.TYPE.equals(cls)) {
return false;
}
if (Float.TYPE.equals(cls)) {
return Double.TYPE.equals(toClass);
}
if (Character.TYPE.equals(cls)) {
return Integer.TYPE.equals(toClass)
|| Long.TYPE.equals(toClass)
|| Float.TYPE.equals(toClass)
|| Double.TYPE.equals(toClass);
}
if (Short.TYPE.equals(cls)) {
return Integer.TYPE.equals(toClass)
|| Long.TYPE.equals(toClass)
|| Float.TYPE.equals(toClass)
|| Double.TYPE.equals(toClass);
}
if (Byte.TYPE.equals(cls)) {
return Short.TYPE.equals(toClass)
|| Integer.TYPE.equals(toClass)
|| Long.TYPE.equals(toClass)
|| Float.TYPE.equals(toClass)
|| Double.TYPE.equals(toClass);
}
// should never get here
return false;
}
return toClass.isAssignableFrom(cls);
}
// Inner class
// ----------------------------------------------------------------------
/**
* Is the specified class an inner class or static nested class.
* * @param cls the class to check * @returntrue
if the class is an inner or static nested class,
* false if not or null
*/
public static boolean isInnerClass(Class cls) {
if (cls == null) {
return false;
}
return (cls.getName().indexOf(INNER_CLASS_SEPARATOR_CHAR) >= 0);
}
}