一、前言
1.基于链接PreparedStatemen的准备处理语句类,对不同类型数据赋值转换适配,并通过ClassUtils的resolvePrimitiveClassName得到给定的简单封装类型的简单类型,具体代码如下SqlExecutor类所示
import java.sql.Array;@b@import java.sql.Connection;@b@import java.sql.DriverManager;@b@import java.sql.PreparedStatement;@b@import java.sql.SQLException;@b@import java.util.Properties;@b@import com.woopa.common.util.ClassUtils;@b@@b@public class SqlExecutor {@b@ @b@ static Properties prop = null;@b@ @b@ static{@b@ prop = new Properties();@b@ try {@b@ prop.load(SqlExecutor.class.getClassLoader().getResourceAsStream("db.properties"));@b@ Class.forName(prop.getProperty("jdbc.driver"));@b@ } catch (Throwable e) {@b@ e.printStackTrace();@b@ }@b@ }@b@@b@ private Connection conn;@b@ private boolean readOnly;@b@ private boolean autoCommit;@b@ private String catalog;@b@ private int transactionIsolation = 2;@b@ @b@ public boolean isReadOnly() {@b@ return readOnly;@b@ }@b@@b@ public void setReadOnly(boolean readOnly) {@b@ this.readOnly = readOnly;@b@ }@b@@b@ public boolean isAutoCommit() {@b@ return autoCommit;@b@ }@b@@b@ public void setAutoCommit(boolean autoCommit) {@b@ this.autoCommit = autoCommit;@b@ }@b@ @b@ public String getCatalog() {@b@ return catalog;@b@ }@b@@b@ public void setCatalog(String catalog) {@b@ this.catalog = catalog;@b@ }@b@@b@ public int getTransactionIsolation() {@b@ return transactionIsolation;@b@ }@b@@b@ public void setTransactionIsolation(int transactionIsolation) {@b@ this.transactionIsolation = transactionIsolation;@b@ }@b@@b@ /**@b@ * 执行sql@b@ * @param sql 脚本@b@ * @return 执行结果成功与否@b@ */@b@ public boolean execute(final String sql,final Object... params) {@b@ return (Boolean) doExecute(sql, new PreparedStatementCallback(){@b@ public Object execute(Connection conn, PreparedStatement stmt)@b@ throws SQLException {@b@ setParameters(stmt, params);@b@ return stmt.execute();@b@ }@b@ });@b@ }@b@ @b@ public Object execute(String sql, PreparedStatementCallback callback){@b@ return doExecute(sql, callback);@b@ }@b@ @b@ public Object execute(ConnectionCallback callback){@b@ return doExecute(callback);@b@ }@b@ @b@ private Object doExecute(ConnectionCallback callback){@b@ Object result = null;@b@ try {@b@ conn = getConnection();@b@ @b@ beforeExecute(conn);@b@ @b@ result = callback.execute(conn);@b@ @b@ conn.commit();@b@ } catch (SQLException e) {@b@ try {@b@ conn.rollback();@b@ } catch (SQLException e1) {@b@ System.out.println(e1.getMessage());@b@ }@b@ throw new RuntimeException(e);@b@ }finally{@b@ try {@b@ if(conn != null)conn.close();@b@ } catch (SQLException e) {@b@ System.out.println(e.getMessage());@b@ }@b@ }@b@ return result;@b@ }@b@ @b@ private Object doExecute(String sql, PreparedStatementCallback callback) {@b@ if(sql == null) return null;@b@ PreparedStatement stmt = null;@b@ Object result = null;@b@ try {@b@ conn = getConnection();@b@ @b@ beforeExecute(conn);@b@ @b@ stmt = conn.prepareStatement(sql);@b@ result = callback.execute(conn, stmt);@b@ @b@ conn.commit();@b@ } catch (SQLException e) {@b@ try {@b@ conn.rollback();@b@ } catch (SQLException e1) {@b@ System.out.println(e1.getMessage());@b@ }@b@ throw new RuntimeException(e);@b@ }finally{@b@ try {@b@ if(stmt != null)stmt.close();@b@ if(conn != null)conn.close();@b@ } catch (SQLException e) {@b@ System.out.println(e.getMessage());@b@ }@b@ }@b@ return result;@b@ }@b@ @b@ protected void beforeExecute(Connection conn) throws SQLException {@b@ conn.setAutoCommit(autoCommit);@b@ conn.setReadOnly(readOnly);@b@ conn.setTransactionIsolation(transactionIsolation);@b@ if(catalog != null) conn.setCatalog(catalog);@b@ }@b@ @b@ protected void setParameters(PreparedStatement ps, Object[] params)@b@ throws SQLException {@b@ for(int i=0; i<params.length; i++){@b@ setValue(ps, params[i], i+1);@b@ }@b@ }@b@ @b@ public Connection getCurrentConnection(){@b@ return conn;@b@ }@b@ @b@ private Connection getConnection() throws SQLException {@b@ if(conn == null || conn.isClosed()){@b@ conn = DriverManager.getConnection(prop.getProperty("jdbc.url")@b@ , prop.getProperty("jdbc.username")@b@ , prop.getProperty("jdbc.password"));@b@ }@b@ //conn = dataSource.getConnection();@b@ return conn;@b@ }@b@ @b@ protected void setValue(PreparedStatement ps , Object value, int index)@b@ throws SQLException {@b@ if(value == null){@b@ ps.setNull(index, java.sql.Types.NULL);@b@ return;@b@ }@b@ Class<?> type = value.getClass();@b@ if(ClassUtils.isPrimitiveWrapper(type)){@b@ type = ClassUtils.resolvePrimitiveClassName(type);@b@ }@b@ if(int.class.isAssignableFrom(type)){@b@ ps.setInt(index, (Integer)value);@b@ }else if(String.class.isAssignableFrom(type)){@b@ ps.setString(index, (String)value);@b@ }else if(long.class.isAssignableFrom(type)){@b@ ps.setLong(index, (Long)value);@b@ }else if(boolean.class.isAssignableFrom(type)){@b@ ps.setBoolean(index, (Boolean)value);@b@ }else if(double.class.isAssignableFrom(type)){@b@ ps.setDouble(index, (Double)value);@b@ }else if(char.class.isAssignableFrom(type)){@b@ ps.setString(index, (Character)value+"");@b@ }else if(short.class.isAssignableFrom(type)){@b@ ps.setShort(index, (Short)value);@b@ }else if(float.class.isAssignableFrom(type)){@b@ ps.setFloat(index, (Float)value);@b@ }else if(byte.class.isAssignableFrom(type)){@b@ ps.setByte(index, (Byte)value);@b@ }else if(type.isArray()){@b@ ps.setArray(index, (Array)value);@b@ }else if(value instanceof java.sql.Timestamp){@b@ ps.setTimestamp(index, (java.sql.Timestamp) value);@b@ }else if(value instanceof java.sql.Date){@b@ ps.setDate(index, (java.sql.Date)value );@b@ }else if(value instanceof java.util.Date){@b@ ps.setDate(index, new java.sql.Date( ((java.util.Date)value).getTime() ));@b@ }else if(value instanceof java.sql.Time){@b@ ps.setTime(index, (java.sql.Time)value );@b@ }@b@ }@b@ @b@ public static interface PreparedStatementCallback{@b@ Object execute(Connection conn, PreparedStatement stmt) throws SQLException;@b@ }@b@ @b@ public static interface ConnectionCallback{@b@ Object execute(Connection conn) throws SQLException;@b@ }@b@}
2.ClassUtils类代码如下
import java.beans.Introspector;@b@import java.lang.reflect.Array;@b@import java.lang.reflect.Constructor;@b@import java.lang.reflect.Method;@b@import java.lang.reflect.Modifier;@b@import java.lang.reflect.Proxy;@b@import java.util.ArrayList;@b@import java.util.Arrays;@b@import java.util.Collection;@b@import java.util.Collections;@b@import java.util.Date;@b@import java.util.HashMap;@b@import java.util.HashSet;@b@import java.util.Iterator;@b@import java.util.LinkedHashSet;@b@import java.util.List;@b@import java.util.Map;@b@import java.util.Set; @b@ @b@public abstract class ClassUtils {@b@@b@ /** Suffix for array class names: "[]" */@b@ public static final String ARRAY_SUFFIX = "[]";@b@@b@ /** Prefix for internal array class names: "[" */@b@ private static final String INTERNAL_ARRAY_PREFIX = "[";@b@@b@ /** Prefix for internal non-primitive array class names: "[L" */@b@ private static final String NON_PRIMITIVE_ARRAY_PREFIX = "[L";@b@@b@ /** The package separator character '.' */@b@ private static final char PACKAGE_SEPARATOR = '.';@b@@b@ /** The inner class separator character '$' */@b@ private static final char INNER_CLASS_SEPARATOR = '$';@b@@b@ /** The CGLIB class separator character "$$" */@b@ public static final String CGLIB_CLASS_SEPARATOR = "$$";@b@@b@ /** The ".class" file suffix */@b@ public static final String CLASS_FILE_SUFFIX = ".class";@b@@b@@b@ /**@b@ * Map with primitive wrapper type as key and corresponding primitive@b@ * type as value, for example: Integer.class -> int.class.@b@ */@b@ private static final Map<Class, Class> primitiveWrapperTypeMap = new HashMap<Class, Class>(8);@b@@b@ /**@b@ * Map with primitive type as key and corresponding wrapper@b@ * type as value, for example: int.class -> Integer.class.@b@ */@b@ private static final Map<Class, Class> primitiveTypeToWrapperMap = new HashMap<Class, Class>(8);@b@@b@ /**@b@ * Map with primitive type name as key and corresponding primitive@b@ * type as value, for example: "int" -> "int.class".@b@ */@b@ private static final Map<String, Class> primitiveTypeNameMap = new HashMap<String, Class>(16);@b@@b@ /**@b@ * Map with common "java.lang" class name as key and corresponding Class as value.@b@ * Primarily for efficient deserialization of remote invocations.@b@ */@b@ private static final Map<String, Class> commonClassCache = new HashMap<String, Class>(32);@b@@b@@b@ static {@b@ primitiveWrapperTypeMap.put(Boolean.class, boolean.class);@b@ primitiveWrapperTypeMap.put(Byte.class, byte.class);@b@ primitiveWrapperTypeMap.put(Character.class, char.class);@b@ primitiveWrapperTypeMap.put(Double.class, double.class);@b@ primitiveWrapperTypeMap.put(Float.class, float.class);@b@ primitiveWrapperTypeMap.put(Integer.class, int.class);@b@ primitiveWrapperTypeMap.put(Long.class, long.class);@b@ primitiveWrapperTypeMap.put(Short.class, short.class);@b@@b@ for (Map.Entry<Class, Class> entry : primitiveWrapperTypeMap.entrySet()) {@b@ primitiveTypeToWrapperMap.put(entry.getValue(), entry.getKey());@b@ registerCommonClasses(entry.getKey());@b@ }@b@@b@ Set<Class> primitiveTypes = new HashSet<Class>(16);@b@ primitiveTypes.addAll(primitiveWrapperTypeMap.values());@b@ primitiveTypes.addAll(Arrays.asList(@b@ boolean[].class, byte[].class, char[].class, double[].class,@b@ float[].class, int[].class, long[].class, short[].class));@b@ for (Class primitiveType : primitiveTypes) {@b@ primitiveTypeNameMap.put(primitiveType.getName(), primitiveType);@b@ }@b@@b@ registerCommonClasses(Boolean[].class, Byte[].class, Character[].class, Double[].class,@b@ Float[].class, Integer[].class, Long[].class, Short[].class);@b@ registerCommonClasses(Number.class, Number[].class, String.class, String[].class,@b@ Object.class, Object[].class, Class.class, Class[].class);@b@ registerCommonClasses(Throwable.class, Exception.class, RuntimeException.class,@b@ Error.class, StackTraceElement.class, StackTraceElement[].class);@b@ }@b@@b@@b@ /**@b@ * Register the given common classes with the ClassUtils cache.@b@ */@b@ private static void registerCommonClasses(Class... commonClasses) {@b@ for (Class clazz : commonClasses) {@b@ commonClassCache.put(clazz.getName(), clazz);@b@ }@b@ }@b@@b@ /**@b@ * Return the default ClassLoader to use: typically the thread context@b@ * ClassLoader, if available; the ClassLoader that loaded the ClassUtils@b@ * class will be used as fallback.@b@ * <p>Call this method if you intend to use the thread context ClassLoader@b@ * in a scenario where you absolutely need a non-null ClassLoader reference:@b@ * for example, for class path resource loading (but not necessarily for@b@ * <code>Class.forName</code>, which accepts a <code>null</code> ClassLoader@b@ * reference as well).@b@ * @return the default ClassLoader (never <code>null</code>)@b@ * @see java.lang.Thread#getContextClassLoader()@b@ */@b@ public static ClassLoader getDefaultClassLoader() {@b@ ClassLoader cl = null;@b@ try {@b@ cl = Thread.currentThread().getContextClassLoader();@b@ }@b@ catch (Throwable ex) {@b@ // Cannot access thread context ClassLoader - falling back to system class loader...@b@ }@b@ if (cl == null) {@b@ // No thread context class loader -> use class loader of this class.@b@ cl = ClassUtils.class.getClassLoader();@b@ }@b@ return cl;@b@ }@b@@b@ /**@b@ * Override the thread context ClassLoader with the environment's bean ClassLoader@b@ * if necessary, i.e. if the bean ClassLoader is not equivalent to the thread@b@ * context ClassLoader already.@b@ * @param classLoaderToUse the actual ClassLoader to use for the thread context@b@ * @return the original thread context ClassLoader, or <code>null</code> if not overridden@b@ */@b@ public static ClassLoader overrideThreadContextClassLoader(ClassLoader classLoaderToUse) {@b@ Thread currentThread = Thread.currentThread();@b@ ClassLoader threadContextClassLoader = currentThread.getContextClassLoader();@b@ if (classLoaderToUse != null && !classLoaderToUse.equals(threadContextClassLoader)) {@b@ currentThread.setContextClassLoader(classLoaderToUse);@b@ return threadContextClassLoader;@b@ }@b@ else {@b@ return null;@b@ }@b@ }@b@@b@ /**@b@ * Replacement for <code>Class.forName()</code> that also returns Class instances@b@ * for primitives (e.g."int") and array class names (e.g. "String[]").@b@ * Furthermore, it is also capable of resolving inner class names in Java source@b@ * style (e.g. "java.lang.Thread.State" instead of "java.lang.Thread$State").@b@ * @param name the name of the Class@b@ * @param classLoader the class loader to use@b@ * (may be <code>null</code>, which indicates the default class loader)@b@ * @return Class instance for the supplied name@b@ * @throws ClassNotFoundException if the class was not found@b@ * @throws LinkageError if the class file could not be loaded@b@ * @see Class#forName(String, boolean, ClassLoader)@b@ */@b@ public static Class forName(String name, ClassLoader classLoader) throws ClassNotFoundException, LinkageError {@b@ Assert.notNull(name, "Name must not be null");@b@@b@ Class clazz = resolvePrimitiveClassName(name);@b@ if (clazz == null) {@b@ clazz = commonClassCache.get(name);@b@ }@b@ if (clazz != null) {@b@ return clazz;@b@ }@b@@b@ // "java.lang.String[]" style arrays@b@ if (name.endsWith(ARRAY_SUFFIX)) {@b@ String elementClassName = name.substring(0, name.length() - ARRAY_SUFFIX.length());@b@ Class elementClass = forName(elementClassName, classLoader);@b@ return Array.newInstance(elementClass, 0).getClass();@b@ }@b@@b@ // "[Ljava.lang.String;" style arrays@b@ if (name.startsWith(NON_PRIMITIVE_ARRAY_PREFIX) && name.endsWith(";")) {@b@ String elementName = name.substring(NON_PRIMITIVE_ARRAY_PREFIX.length(), name.length() - 1);@b@ Class elementClass = forName(elementName, classLoader);@b@ return Array.newInstance(elementClass, 0).getClass();@b@ }@b@@b@ // "[[I" or "[[Ljava.lang.String;" style arrays@b@ if (name.startsWith(INTERNAL_ARRAY_PREFIX)) {@b@ String elementName = name.substring(INTERNAL_ARRAY_PREFIX.length());@b@ Class elementClass = forName(elementName, classLoader);@b@ return Array.newInstance(elementClass, 0).getClass();@b@ }@b@@b@ ClassLoader classLoaderToUse = classLoader;@b@ if (classLoaderToUse == null) {@b@ classLoaderToUse = getDefaultClassLoader();@b@ }@b@ try {@b@ return classLoaderToUse.loadClass(name);@b@ }@b@ catch (ClassNotFoundException ex) {@b@ int lastDotIndex = name.lastIndexOf('.');@b@ if (lastDotIndex != -1) {@b@ String innerClassName = name.substring(0, lastDotIndex) + '$' + name.substring(lastDotIndex + 1);@b@ try {@b@ return classLoaderToUse.loadClass(innerClassName);@b@ }@b@ catch (ClassNotFoundException ex2) {@b@ // swallow - let original exception get through@b@ }@b@ }@b@ throw ex;@b@ }@b@ }@b@@b@ /**@b@ * Resolve the given class name into a Class instance. Supports@b@ * primitives (like "int") and array class names (like "String[]").@b@ * <p>This is effectively equivalent to the <code>forName</code>@b@ * method with the same arguments, with the only difference being@b@ * the exceptions thrown in case of class loading failure.@b@ * @param className the name of the Class@b@ * @param classLoader the class loader to use@b@ * (may be <code>null</code>, which indicates the default class loader)@b@ * @return Class instance for the supplied name@b@ * @throws IllegalArgumentException if the class name was not resolvable@b@ * (that is, the class could not be found or the class file could not be loaded)@b@ * @see #forName(String, ClassLoader)@b@ */@b@ public static Class resolveClassName(String className, ClassLoader classLoader) throws IllegalArgumentException {@b@ try {@b@ return forName(className, classLoader);@b@ }@b@ catch (ClassNotFoundException ex) {@b@ throw new IllegalArgumentException("Cannot find class [" + className + "]", ex);@b@ }@b@ catch (LinkageError ex) {@b@ throw new IllegalArgumentException(@b@ "Error loading class [" + className + "]: problem with class file or dependent class.", ex);@b@ }@b@ }@b@@b@ /**@b@ * Resolve the given class name as primitive class, if appropriate,@b@ * according to the JVM's naming rules for primitive classes.@b@ * <p>Also supports the JVM's internal class names for primitive arrays.@b@ * Does <i>not</i> support the "[]" suffix notation for primitive arrays;@b@ * this is only supported by {@link #forName(String, ClassLoader)}.@b@ * @param name the name of the potentially primitive class@b@ * @return the primitive class, or <code>null</code> if the name does not denote@b@ * a primitive class or primitive array class@b@ */@b@ public static Class resolvePrimitiveClassName(String name) {@b@ Class result = null;@b@ // Most class names will be quite long, considering that they@b@ // SHOULD sit in a package, so a length check is worthwhile.@b@ if (name != null && name.length() <= 8) {@b@ // Could be a primitive - likely.@b@ result = primitiveTypeNameMap.get(name);@b@ }@b@ return result;@b@ }@b@ /**@b@ * 得到给定的简单封装类型的简单类型@b@ * @param wrapperType@b@ * @return@b@ */@b@ public static Class resolvePrimitiveClassName(Class wrapperType){@b@ return primitiveWrapperTypeMap.get(wrapperType);@b@ }@b@@b@ /**@b@ * Determine whether the {@link Class} identified by the supplied name is present@b@ * and can be loaded. Will return <code>false</code> if either the class or@b@ * one of its dependencies is not present or cannot be loaded.@b@ * @param className the name of the class to check@b@ * @param classLoader the class loader to use@b@ * (may be <code>null</code>, which indicates the default class loader)@b@ * @return whether the specified class is present@b@ */@b@ public static boolean isPresent(String className, ClassLoader classLoader) {@b@ try {@b@ forName(className, classLoader);@b@ return true;@b@ }@b@ catch (Throwable ex) {@b@ // Class or one of its dependencies is not present...@b@ return false;@b@ }@b@ }@b@@b@ /**@b@ * Return the user-defined class for the given instance: usually simply@b@ * the class of the given instance, but the original class in case of a@b@ * CGLIB-generated subclass.@b@ * @param instance the instance to check@b@ * @return the user-defined class@b@ */@b@ public static Class getUserClass(Object instance) {@b@ Assert.notNull(instance, "Instance must not be null");@b@ return getUserClass(instance.getClass());@b@ }@b@@b@ /**@b@ * Return the user-defined class for the given class: usually simply the given@b@ * class, but the original class in case of a CGLIB-generated subclass.@b@ * @param clazz the class to check@b@ * @return the user-defined class@b@ */@b@ public static Class getUserClass(Class clazz) {@b@ return (clazz != null && clazz.getName().contains(CGLIB_CLASS_SEPARATOR) ?@b@ clazz.getSuperclass() : clazz);@b@ }@b@@b@ /**@b@ * Check whether the given class is cache-safe in the given context,@b@ * i.e. whether it is loaded by the given ClassLoader or a parent of it.@b@ * @param clazz the class to analyze@b@ * @param classLoader the ClassLoader to potentially cache metadata in@b@ */@b@ public static boolean isCacheSafe(Class clazz, ClassLoader classLoader) {@b@ Assert.notNull(clazz, "Class must not be null");@b@ ClassLoader target = clazz.getClassLoader();@b@ if (target == null) {@b@ return false;@b@ }@b@ ClassLoader cur = classLoader;@b@ if (cur == target) {@b@ return true;@b@ }@b@ while (cur != null) {@b@ cur = cur.getParent();@b@ if (cur == target) {@b@ return true;@b@ }@b@ }@b@ return false;@b@ }@b@@b@@b@ /**@b@ * Get the class name without the qualified package name.@b@ * @param className the className to get the short name for@b@ * @return the class name of the class without the package name@b@ * @throws IllegalArgumentException if the className is empty@b@ */@b@ public static String getShortName(String className) {@b@ Assert.hasLength(className, "Class name must not be empty");@b@ int lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR);@b@ int nameEndIndex = className.indexOf(CGLIB_CLASS_SEPARATOR);@b@ if (nameEndIndex == -1) {@b@ nameEndIndex = className.length();@b@ }@b@ String shortName = className.substring(lastDotIndex + 1, nameEndIndex);@b@ shortName = shortName.replace(INNER_CLASS_SEPARATOR, PACKAGE_SEPARATOR);@b@ return shortName;@b@ }@b@@b@ /**@b@ * Get the class name without the qualified package name.@b@ * @param clazz the class to get the short name for@b@ * @return the class name of the class without the package name@b@ */@b@ public static String getShortName(Class clazz) {@b@ return getShortName(getQualifiedName(clazz));@b@ }@b@@b@ /**@b@ * Return the short string name of a Java class in uncapitalized JavaBeans@b@ * property format. Strips the outer class name in case of an inner class.@b@ * @param clazz the class@b@ * @return the short name rendered in a standard JavaBeans property format@b@ * @see java.beans.Introspector#decapitalize(String)@b@ */@b@ public static String getShortNameAsProperty(Class clazz) {@b@ String shortName = ClassUtils.getShortName(clazz);@b@ int dotIndex = shortName.lastIndexOf('.');@b@ shortName = (dotIndex != -1 ? shortName.substring(dotIndex + 1) : shortName);@b@ return Introspector.decapitalize(shortName);@b@ }@b@@b@ /**@b@ * Determine the name of the class file, relative to the containing@b@ * package: e.g. "String.class"@b@ * @param clazz the class@b@ * @return the file name of the ".class" file@b@ */@b@ public static String getClassFileName(Class clazz) {@b@ Assert.notNull(clazz, "Class must not be null");@b@ String className = clazz.getName();@b@ int lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR);@b@ return className.substring(lastDotIndex + 1) + CLASS_FILE_SUFFIX;@b@ }@b@@b@ /**@b@ * Determine the name of the package of the given class:@b@ * e.g. "java.lang" for the <code>java.lang.String</code> class.@b@ * @param clazz the class@b@ * @return the package name, or the empty String if the class@b@ * is defined in the default package@b@ */@b@ public static String getPackageName(Class clazz) {@b@ Assert.notNull(clazz, "Class must not be null");@b@ String className = clazz.getName();@b@ int lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR);@b@ return (lastDotIndex != -1 ? className.substring(0, lastDotIndex) : "");@b@ }@b@@b@ /**@b@ * Return the qualified name of the given class: usually simply@b@ * the class name, but component type class name + "[]" for arrays.@b@ * @param clazz the class@b@ * @return the qualified name of the class@b@ */@b@ public static String getQualifiedName(Class clazz) {@b@ Assert.notNull(clazz, "Class must not be null");@b@ if (clazz.isArray()) {@b@ return getQualifiedNameForArray(clazz);@b@ }@b@ else {@b@ return clazz.getName();@b@ }@b@ }@b@@b@ /**@b@ * Build a nice qualified name for an array:@b@ * component type class name + "[]".@b@ * @param clazz the array class@b@ * @return a qualified name for the array class@b@ */@b@ private static String getQualifiedNameForArray(Class clazz) {@b@ StringBuilder result = new StringBuilder();@b@ while (clazz.isArray()) {@b@ clazz = clazz.getComponentType();@b@ result.append(ClassUtils.ARRAY_SUFFIX);@b@ }@b@ result.insert(0, clazz.getName());@b@ return result.toString();@b@ }@b@@b@ /**@b@ * Return the qualified name of the given method, consisting of@b@ * fully qualified interface/class name + "." + method name.@b@ * @param method the method@b@ * @return the qualified name of the method@b@ */@b@ public static String getQualifiedMethodName(Method method) {@b@ Assert.notNull(method, "Method must not be null");@b@ return method.getDeclaringClass().getName() + "." + method.getName();@b@ }@b@@b@ /**@b@ * Return a descriptive name for the given object's type: usually simply@b@ * the class name, but component type class name + "[]" for arrays,@b@ * and an appended list of implemented interfaces for JDK proxies.@b@ * @param value the value to introspect@b@ * @return the qualified name of the class@b@ */@b@ public static String getDescriptiveType(Object value) {@b@ if (value == null) {@b@ return null;@b@ }@b@ Class clazz = value.getClass();@b@ if (Proxy.isProxyClass(clazz)) {@b@ StringBuilder result = new StringBuilder(clazz.getName());@b@ result.append(" implementing ");@b@ Class[] ifcs = clazz.getInterfaces();@b@ for (int i = 0; i < ifcs.length; i++) {@b@ result.append(ifcs[i].getName());@b@ if (i < ifcs.length - 1) {@b@ result.append(',');@b@ }@b@ }@b@ return result.toString();@b@ }@b@ else if (clazz.isArray()) {@b@ return getQualifiedNameForArray(clazz);@b@ }@b@ else {@b@ return clazz.getName();@b@ }@b@ }@b@@b@ /**@b@ * Check whether the given class matches the user-specified type name.@b@ * @param clazz the class to check@b@ * @param typeName the type name to match@b@ */@b@ public static boolean matchesTypeName(Class clazz, String typeName) {@b@ return (typeName != null &&@b@ (typeName.equals(clazz.getName()) || typeName.equals(clazz.getSimpleName()) ||@b@ (clazz.isArray() && typeName.equals(getQualifiedNameForArray(clazz)))));@b@ }@b@@b@@b@ /**@b@ * Determine whether the given class has a public constructor with the given signature.@b@ * <p>Essentially translates <code>NoSuchMethodException</code> to "false".@b@ * @param clazz the clazz to analyze@b@ * @param paramTypes the parameter types of the method@b@ * @return whether the class has a corresponding constructor@b@ * @see java.lang.Class#getMethod@b@ */@b@ public static boolean hasConstructor(Class clazz, Class... paramTypes) {@b@ return (getConstructorIfAvailable(clazz, paramTypes) != null);@b@ }@b@@b@ /**@b@ * Determine whether the given class has a public constructor with the given signature,@b@ * and return it if available (else return <code>null</code>).@b@ * <p>Essentially translates <code>NoSuchMethodException</code> to <code>null</code>.@b@ * @param clazz the clazz to analyze@b@ * @param paramTypes the parameter types of the method@b@ * @return the constructor, or <code>null</code> if not found@b@ * @see java.lang.Class#getConstructor@b@ */@b@ public static <T> Constructor<T> getConstructorIfAvailable(Class<T> clazz, Class... paramTypes) {@b@ Assert.notNull(clazz, "Class must not be null");@b@ try {@b@ return clazz.getConstructor(paramTypes);@b@ }@b@ catch (NoSuchMethodException ex) {@b@ return null;@b@ }@b@ }@b@@b@ /**@b@ * Determine whether the given class has a method with the given signature.@b@ * <p>Essentially translates <code>NoSuchMethodException</code> to "false".@b@ * @param clazz the clazz to analyze@b@ * @param methodName the name of the method@b@ * @param paramTypes the parameter types of the method@b@ * @return whether the class has a corresponding method@b@ * @see java.lang.Class#getMethod@b@ */@b@ public static boolean hasMethod(Class clazz, String methodName, Class... paramTypes) {@b@ return (getMethodIfAvailable(clazz, methodName, paramTypes) != null);@b@ }@b@@b@ /**@b@ * Determine whether the given class has a method with the given signature,@b@ * and return it if available (else return <code>null</code>).@b@ * <p>Essentially translates <code>NoSuchMethodException</code> to <code>null</code>.@b@ * @param clazz the clazz to analyze@b@ * @param methodName the name of the method@b@ * @param paramTypes the parameter types of the method@b@ * @return the method, or <code>null</code> if not found@b@ * @see java.lang.Class#getMethod@b@ */@b@ public static Method getMethodIfAvailable(Class clazz, String methodName, Class... paramTypes) {@b@ Assert.notNull(clazz, "Class must not be null");@b@ Assert.notNull(methodName, "Method name must not be null");@b@ try {@b@ return clazz.getMethod(methodName, paramTypes);@b@ }@b@ catch (NoSuchMethodException ex) {@b@ return null;@b@ }@b@ }@b@@b@ /**@b@ * Return the number of methods with a given name (with any argument types),@b@ * for the given class and/or its superclasses. Includes non-public methods.@b@ * @param clazz the clazz to check@b@ * @param methodName the name of the method@b@ * @return the number of methods with the given name@b@ */@b@ public static int getMethodCountForName(Class clazz, String methodName) {@b@ Assert.notNull(clazz, "Class must not be null");@b@ Assert.notNull(methodName, "Method name must not be null");@b@ int count = 0;@b@ Method[] declaredMethods = clazz.getDeclaredMethods();@b@ for (Method method : declaredMethods) {@b@ if (methodName.equals(method.getName())) {@b@ count++;@b@ }@b@ }@b@ Class[] ifcs = clazz.getInterfaces();@b@ for (Class ifc : ifcs) {@b@ count += getMethodCountForName(ifc, methodName);@b@ }@b@ if (clazz.getSuperclass() != null) {@b@ count += getMethodCountForName(clazz.getSuperclass(), methodName);@b@ }@b@ return count;@b@ }@b@@b@ /**@b@ * Does the given class or one of its superclasses at least have one or more@b@ * methods with the supplied name (with any argument types)?@b@ * Includes non-public methods.@b@ * @param clazz the clazz to check@b@ * @param methodName the name of the method@b@ * @return whether there is at least one method with the given name@b@ */@b@ public static boolean hasAtLeastOneMethodWithName(Class clazz, String methodName) {@b@ Assert.notNull(clazz, "Class must not be null");@b@ Assert.notNull(methodName, "Method name must not be null");@b@ Method[] declaredMethods = clazz.getDeclaredMethods();@b@ for (Method method : declaredMethods) {@b@ if (method.getName().equals(methodName)) {@b@ return true;@b@ }@b@ }@b@ Class[] ifcs = clazz.getInterfaces();@b@ for (Class ifc : ifcs) {@b@ if (hasAtLeastOneMethodWithName(ifc, methodName)) {@b@ return true;@b@ }@b@ }@b@ return (clazz.getSuperclass() != null && hasAtLeastOneMethodWithName(clazz.getSuperclass(), methodName));@b@ }@b@@b@@b@ /**@b@ * Return a public static method of a class.@b@ * @param methodName the static method name@b@ * @param clazz the class which defines the method@b@ * @param args the parameter types to the method@b@ * @return the static method, or <code>null</code> if no static method was found@b@ * @throws IllegalArgumentException if the method name is blank or the clazz is null@b@ */@b@ public static Method getStaticMethod(Class clazz, String methodName, Class... args) {@b@ Assert.notNull(clazz, "Class must not be null");@b@ Assert.notNull(methodName, "Method name must not be null");@b@ try {@b@ Method method = clazz.getMethod(methodName, args);@b@ return Modifier.isStatic(method.getModifiers()) ? method : null;@b@ }@b@ catch (NoSuchMethodException ex) {@b@ return null;@b@ }@b@ }@b@@b@@b@ /**@b@ * Check if the given class represents a primitive wrapper,@b@ * i.e. Boolean, Byte, Character, Short, Integer, Long, Float, or Double.@b@ * @param clazz the class to check@b@ * @return whether the given class is a primitive wrapper class@b@ */@b@ public static boolean isPrimitiveWrapper(Class clazz) {@b@ Assert.notNull(clazz, "Class must not be null");@b@ return primitiveWrapperTypeMap.containsKey(clazz);@b@ }@b@@b@ /**@b@ * Check if the given class represents a primitive (i.e. boolean, byte,@b@ * char, short, int, long, float, or double) or a primitive wrapper@b@ * (i.e. Boolean, Byte, Character, Short, Integer, Long, Float, or Double).@b@ * @param clazz the class to check@b@ * @return whether the given class is a primitive or primitive wrapper class@b@ */@b@ public static boolean isPrimitiveOrWrapper(Class clazz) {@b@ Assert.notNull(clazz, "Class must not be null");@b@ return (clazz.isPrimitive() || isPrimitiveWrapper(clazz));@b@ }@b@@b@ /**@b@ * Check if the given class represents an array of primitives,@b@ * i.e. boolean, byte, char, short, int, long, float, or double.@b@ * @param clazz the class to check@b@ * @return whether the given class is a primitive array class@b@ */@b@ public static boolean isPrimitiveArray(Class clazz) {@b@ Assert.notNull(clazz, "Class must not be null");@b@ return (clazz.isArray() && clazz.getComponentType().isPrimitive());@b@ }@b@@b@ /**@b@ * Check if the given class represents an array of primitive wrappers,@b@ * i.e. Boolean, Byte, Character, Short, Integer, Long, Float, or Double.@b@ * @param clazz the class to check@b@ * @return whether the given class is a primitive wrapper array class@b@ */@b@ public static boolean isPrimitiveWrapperArray(Class clazz) {@b@ Assert.notNull(clazz, "Class must not be null");@b@ return (clazz.isArray() && isPrimitiveWrapper(clazz.getComponentType()));@b@ }@b@@b@ /**@b@ * Resolve the given class if it is a primitive class,@b@ * returning the corresponding primitive wrapper type instead.@b@ * @param clazz the class to check@b@ * @return the original class, or a primitive wrapper for the original primitive type@b@ */@b@ public static Class resolvePrimitiveIfNecessary(Class clazz) {@b@ Assert.notNull(clazz, "Class must not be null");@b@ return (clazz.isPrimitive() ? primitiveTypeToWrapperMap.get(clazz) : clazz);@b@ }@b@@b@ /**@b@ * Check if the right-hand side type may be assigned to the left-hand side@b@ * type, assuming setting by reflection. Considers primitive wrapper@b@ * classes as assignable to the corresponding primitive types.@b@ * @param lhsType the target type@b@ * @param rhsType the value type that should be assigned to the target type@b@ * @return if the target type is assignable from the value type@b@ * @see TypeUtils#isAssignable@b@ */@b@ public static boolean isAssignable(Class lhsType, Class rhsType) {@b@ Assert.notNull(lhsType, "Left-hand side type must not be null");@b@ Assert.notNull(rhsType, "Right-hand side type must not be null");@b@ return (lhsType.isAssignableFrom(rhsType) ||@b@ lhsType.equals(primitiveWrapperTypeMap.get(rhsType)));@b@ }@b@@b@ /**@b@ * Determine if the given type is assignable from the given value,@b@ * assuming setting by reflection. Considers primitive wrapper classes@b@ * as assignable to the corresponding primitive types.@b@ * @param type the target type@b@ * @param value the value that should be assigned to the type@b@ * @return if the type is assignable from the value@b@ */@b@ public static boolean isAssignableValue(Class type, Object value) {@b@ Assert.notNull(type, "Type must not be null");@b@ return (value != null ? isAssignable(type, value.getClass()) : !type.isPrimitive());@b@ }@b@@b@@b@ /**@b@ * Convert a "/"-based resource path to a "."-based fully qualified class name.@b@ * @param resourcePath the resource path pointing to a class@b@ * @return the corresponding fully qualified class name@b@ */@b@ public static String convertResourcePathToClassName(String resourcePath) {@b@ Assert.notNull(resourcePath, "Resource path must not be null");@b@ return resourcePath.replace('/', '.');@b@ }@b@@b@ /**@b@ * Convert a "."-based fully qualified class name to a "/"-based resource path.@b@ * @param className the fully qualified class name@b@ * @return the corresponding resource path, pointing to the class@b@ */@b@ public static String convertClassNameToResourcePath(String className) {@b@ Assert.notNull(className, "Class name must not be null");@b@ return className.replace('.', '/');@b@ }@b@@b@ /**@b@ * Return a path suitable for use with <code>ClassLoader.getResource</code>@b@ * (also suitable for use with <code>Class.getResource</code> by prepending a@b@ * slash ('/') to the return value). Built by taking the package of the specified@b@ * class file, converting all dots ('.') to slashes ('/'), adding a trailing slash@b@ * if necessary, and concatenating the specified resource name to this.@b@ * <br/>As such, this function may be used to build a path suitable for@b@ * loading a resource file that is in the same package as a class file,@b@ * although {@link org.springframework.core.io.ClassPathResource} is usually@b@ * even more convenient.@b@ * @param clazz the Class whose package will be used as the base@b@ * @param resourceName the resource name to append. A leading slash is optional.@b@ * @return the built-up resource path@b@ * @see java.lang.ClassLoader#getResource@b@ * @see java.lang.Class#getResource@b@ */@b@ public static String addResourcePathToPackagePath(Class clazz, String resourceName) {@b@ Assert.notNull(resourceName, "Resource name must not be null");@b@ if (!resourceName.startsWith("/")) {@b@ return classPackageAsResourcePath(clazz) + "/" + resourceName;@b@ }@b@ return classPackageAsResourcePath(clazz) + resourceName;@b@ }@b@@b@ /**@b@ * Given an input class object, return a string which consists of the@b@ * class's package name as a pathname, i.e., all dots ('.') are replaced by@b@ * slashes ('/'). Neither a leading nor trailing slash is added. The result@b@ * could be concatenated with a slash and the name of a resource and fed@b@ * directly to <code>ClassLoader.getResource()</code>. For it to be fed to@b@ * <code>Class.getResource</code> instead, a leading slash would also have@b@ * to be prepended to the returned value.@b@ * @param clazz the input class. A <code>null</code> value or the default@b@ * (empty) package will result in an empty string ("") being returned.@b@ * @return a path which represents the package name@b@ * @see ClassLoader#getResource@b@ * @see Class#getResource@b@ */@b@ public static String classPackageAsResourcePath(Class clazz) {@b@ if (clazz == null) {@b@ return "";@b@ }@b@ String className = clazz.getName();@b@ int packageEndIndex = className.lastIndexOf('.');@b@ if (packageEndIndex == -1) {@b@ return "";@b@ }@b@ String packageName = className.substring(0, packageEndIndex);@b@ return packageName.replace('.', '/');@b@ }@b@@b@ /**@b@ * Build a String that consists of the names of the classes/interfaces@b@ * in the given array.@b@ * <p>Basically like <code>AbstractCollection.toString()</code>, but stripping@b@ * the "class "/"interface " prefix before every class name.@b@ * @param classes a Collection of Class objects (may be <code>null</code>)@b@ * @return a String of form "[com.foo.Bar, com.foo.Baz]"@b@ * @see java.util.AbstractCollection#toString()@b@ */@b@ public static String classNamesToString(Class... classes) {@b@ return classNamesToString(Arrays.asList(classes));@b@ }@b@@b@ /**@b@ * Build a String that consists of the names of the classes/interfaces@b@ * in the given collection.@b@ * <p>Basically like <code>AbstractCollection.toString()</code>, but stripping@b@ * the "class "/"interface " prefix before every class name.@b@ * @param classes a Collection of Class objects (may be <code>null</code>)@b@ * @return a String of form "[com.foo.Bar, com.foo.Baz]"@b@ * @see java.util.AbstractCollection#toString()@b@ */@b@ public static String classNamesToString(Collection<Class> classes) {@b@ if (CollectionUtils.isEmpty(classes)) {@b@ return "[]";@b@ }@b@ StringBuilder sb = new StringBuilder("[");@b@ for (Iterator<Class> it = classes.iterator(); it.hasNext(); ) {@b@ Class clazz = it.next();@b@ sb.append(clazz.getName());@b@ if (it.hasNext()) {@b@ sb.append(", ");@b@ }@b@ }@b@ sb.append("]");@b@ return sb.toString();@b@ }@b@@b@@b@ /**@b@ * Return all interfaces that the given instance implements as array,@b@ * including ones implemented by superclasses.@b@ * @param instance the instance to analyze for interfaces@b@ * @return all interfaces that the given instance implements as array@b@ */@b@ public static Class[] getAllInterfaces(Object instance) {@b@ Assert.notNull(instance, "Instance must not be null");@b@ return getAllInterfacesForClass(instance.getClass());@b@ }@b@@b@ /**@b@ * Return all interfaces that the given class implements as array,@b@ * including ones implemented by superclasses.@b@ * <p>If the class itself is an interface, it gets returned as sole interface.@b@ * @param clazz the class to analyze for interfaces@b@ * @return all interfaces that the given object implements as array@b@ */@b@ public static Class[] getAllInterfacesForClass(Class clazz) {@b@ return getAllInterfacesForClass(clazz, null);@b@ }@b@@b@ /**@b@ * Return all interfaces that the given class implements as array,@b@ * including ones implemented by superclasses.@b@ * <p>If the class itself is an interface, it gets returned as sole interface.@b@ * @param clazz the class to analyze for interfaces@b@ * @param classLoader the ClassLoader that the interfaces need to be visible in@b@ * (may be <code>null</code> when accepting all declared interfaces)@b@ * @return all interfaces that the given object implements as array@b@ */@b@ public static Class[] getAllInterfacesForClass(Class clazz, ClassLoader classLoader) {@b@ Assert.notNull(clazz, "Class must not be null");@b@ if (clazz.isInterface()) {@b@ return new Class[] {clazz};@b@ }@b@ List<Class> interfaces = new ArrayList<Class>();@b@ while (clazz != null) {@b@ Class[] ifcs = clazz.getInterfaces();@b@ for (Class ifc : ifcs) {@b@ if (!interfaces.contains(ifc) &&@b@ (classLoader == null || isVisible(ifc, classLoader))) {@b@ interfaces.add(ifc);@b@ }@b@ }@b@ clazz = clazz.getSuperclass();@b@ }@b@ return interfaces.toArray(new Class[interfaces.size()]);@b@ }@b@@b@ /**@b@ * Return all interfaces that the given instance implements as Set,@b@ * including ones implemented by superclasses.@b@ * @param instance the instance to analyze for interfaces@b@ * @return all interfaces that the given instance implements as Set@b@ */@b@ public static Set<Class> getAllInterfacesAsSet(Object instance) {@b@ Assert.notNull(instance, "Instance must not be null");@b@ return getAllInterfacesForClassAsSet(instance.getClass());@b@ }@b@@b@ /**@b@ * Return all interfaces that the given class implements as Set,@b@ * including ones implemented by superclasses.@b@ * <p>If the class itself is an interface, it gets returned as sole interface.@b@ * @param clazz the class to analyze for interfaces@b@ * @return all interfaces that the given object implements as Set@b@ */@b@ public static Set<Class> getAllInterfacesForClassAsSet(Class clazz) {@b@ return getAllInterfacesForClassAsSet(clazz, null);@b@ }@b@@b@ /**@b@ * Return all interfaces that the given class implements as Set,@b@ * including ones implemented by superclasses.@b@ * <p>If the class itself is an interface, it gets returned as sole interface.@b@ * @param clazz the class to analyze for interfaces@b@ * @param classLoader the ClassLoader that the interfaces need to be visible in@b@ * (may be <code>null</code> when accepting all declared interfaces)@b@ * @return all interfaces that the given object implements as Set@b@ */@b@ public static Set<Class> getAllInterfacesForClassAsSet(Class clazz, ClassLoader classLoader) {@b@ Assert.notNull(clazz, "Class must not be null");@b@ if (clazz.isInterface()) {@b@ return Collections.singleton(clazz);@b@ }@b@ Set<Class> interfaces = new LinkedHashSet<Class>();@b@ while (clazz != null) {@b@ for (int i = 0; i < clazz.getInterfaces().length; i++) {@b@ Class ifc = clazz.getInterfaces()[i];@b@ if (classLoader == null || isVisible(ifc, classLoader)) {@b@ interfaces.add(ifc);@b@ }@b@ }@b@ clazz = clazz.getSuperclass();@b@ }@b@ return interfaces;@b@ }@b@@b@ /**@b@ * Create a composite interface Class for the given interfaces,@b@ * implementing the given interfaces in one single Class.@b@ * <p>This implementation builds a JDK proxy class for the given interfaces.@b@ * @param interfaces the interfaces to merge@b@ * @param classLoader the ClassLoader to create the composite Class in@b@ * @return the merged interface as Class@b@ * @see java.lang.reflect.Proxy#getProxyClass@b@ */@b@ public static Class createCompositeInterface(Class[] interfaces, ClassLoader classLoader) {@b@ Assert.notEmpty(interfaces, "Interfaces must not be empty");@b@ Assert.notNull(classLoader, "ClassLoader must not be null");@b@ return Proxy.getProxyClass(classLoader, interfaces);@b@ }@b@@b@ /**@b@ * Check whether the given class is visible in the given ClassLoader.@b@ * @param clazz the class to check (typically an interface)@b@ * @param classLoader the ClassLoader to check against (may be <code>null</code>,@b@ * in which case this method will always return <code>true</code>)@b@ */@b@ public static boolean isVisible(Class clazz, ClassLoader classLoader) {@b@ if (classLoader == null) {@b@ return true;@b@ }@b@ try {@b@ Class actualClass = classLoader.loadClass(clazz.getName());@b@ return (clazz == actualClass);@b@ // Else: different interface class found...@b@ }@b@ catch (ClassNotFoundException ex) {@b@ // No interface class found...@b@ return false;@b@ }@b@ }@b@ /**@b@ * 判断类对象是否一个非自定义类对象@b@ * 当对象为下列类对象或其子类对象实例之一,则认为是一个非自定义类对象@b@ * Number、String、java.util.Date、java.util.Caldenar、Primitive、Array、Collection@b@ * @param clazz@b@ * @return@b@ */@b@ public static boolean isNotDefinedClass(Class clazz){@b@ return Number.class.isAssignableFrom(clazz)@b@ || ClassUtils.isPrimitiveOrWrapper(clazz) @b@ || String.class.isAssignableFrom(clazz) @b@ || clazz.isArray()@b@ || java.util.Date.class.isAssignableFrom(clazz)@b@ || java.util.Collection.class.isAssignableFrom(clazz)@b@ || java.util.Calendar.class.isAssignableFrom(clazz);@b@ }@b@ @b@ /**@b@ * 判断是否为封装对象实体Bean@b@ * 此方法认为如果类型为Collection或非简单类型及其包装类型并且非字符类型,则为映射类型@b@ * @param clazz@b@ * @return@b@ */@b@ public static boolean isMappingType(Class clazz){@b@ return !( clazz.isPrimitive()@b@ || String.class.isAssignableFrom(clazz)@b@ || Date.class.isAssignableFrom(clazz)@b@ || Number.class.isAssignableFrom(clazz)@b@ );@b@ }@b@}