首页

关于granite源码包ClassUtil类工具类实现获取容器getConstructor、类加载及实例化等操作

标签:granite,ClassUtil,类工具类     发布时间:2018-05-20   

一、前言

基于granite源码包org.granite.util.ClassUtil类工具类,分别对各种类型对象实例化newInstance重载、类加载forName重载、获取getConstructor加载容器、获取路径包getPackageName、获取已加对象加载器getClassLoader等。

二、源码说明

ClassUtil类依赖org.granite.util.StringUtil

package org.granite.util;@b@@b@import java.beans.BeanInfo;@b@import java.beans.Introspector;@b@import java.beans.PropertyDescriptor;@b@import java.lang.reflect.Array;@b@import java.lang.reflect.Constructor;@b@import java.lang.reflect.Field;@b@import java.lang.reflect.GenericArrayType;@b@import java.lang.reflect.InvocationTargetException;@b@import java.lang.reflect.Method;@b@import java.lang.reflect.Modifier;@b@import java.lang.reflect.ParameterizedType;@b@import java.lang.reflect.Type;@b@import java.lang.reflect.TypeVariable;@b@import java.lang.reflect.WildcardType;@b@import java.net.MalformedURLException;@b@import java.net.URL;@b@import java.util.Collections;@b@import java.util.List;@b@import java.util.Map;@b@import java.util.Set;@b@@b@public abstract class ClassUtil@b@{@b@  public static Object newInstance(String type)@b@    throws ClassNotFoundException, InstantiationException, IllegalAccessException@b@  {@b@    return forName(type).newInstance();@b@  }@b@@b@  public static <T> T newInstance(String type, Class<T> cast) throws ClassNotFoundException, InstantiationException, IllegalAccessException@b@  {@b@    return forName(type, cast).newInstance();@b@  }@b@@b@  public static Object newInstance(String type, Class<?>[] argsClass, Object[] argsValues) throws ClassNotFoundException, InstantiationException, IllegalAccessException@b@  {@b@    return newInstance(forName(type), argsClass, argsValues);@b@  }@b@@b@  public static <T> T newInstance(Class<?> type, Class<T> cast)@b@    throws InstantiationException, IllegalAccessException@b@  {@b@    return type.newInstance();@b@  }@b@@b@  public static <T> T newInstance(Class<T> type, Class<?>[] argsClass, Object[] argsValues) throws InstantiationException, IllegalAccessException@b@  {@b@    Object instance = null;@b@    try {@b@      Constructor constructorDef = type.getConstructor(argsClass);@b@      instance = constructorDef.newInstance(argsValues);@b@    } catch (SecurityException e) {@b@      throw new InstantiationException(e.getMessage());@b@    } catch (NoSuchMethodException e) {@b@      throw new InstantiationException(e.getMessage());@b@    } catch (IllegalArgumentException e) {@b@      throw new InstantiationException(e.getMessage());@b@    } catch (InvocationTargetException e) {@b@      throw new InstantiationException(e.getMessage());@b@    }@b@    return instance;@b@  }@b@@b@  public static Class<?> forName(String type) throws ClassNotFoundException {@b@    try {@b@      return ClassUtil.class.getClassLoader().loadClass(type);@b@    } catch (ClassNotFoundException e) {@b@    }@b@    return Thread.currentThread().getContextClassLoader().loadClass(type);@b@  }@b@@b@  public static <T> Class<T> forName(String type, Class<T> cast) throws ClassNotFoundException@b@  {@b@    try@b@    {@b@      return ClassUtil.class.getClassLoader().loadClass(type);@b@    } catch (ClassNotFoundException e) {@b@    }@b@    return Thread.currentThread().getContextClassLoader().loadClass(type);@b@  }@b@@b@  public static Constructor<?> getConstructor(String type, Class<?>[] paramTypes)@b@    throws ClassNotFoundException, NoSuchMethodException@b@  {@b@    return getConstructor(forName(type), paramTypes);@b@  }@b@@b@  public static <T> Constructor<T> getConstructor(Class<T> type, Class<?>[] paramTypes) throws NoSuchMethodException@b@  {@b@    return type.getConstructor(paramTypes);@b@  }@b@@b@  public static <T> List<T> emptyList(Class<T> type) {@b@    return Collections.emptyList();@b@  }@b@@b@  public static <T> Set<T> emptySet(Class<T> type) {@b@    return Collections.emptySet();@b@  }@b@@b@  public static <T, U> Map<T, U> emptyMap(Class<T> keyType, Class<U> valueType) {@b@    return Collections.emptyMap();@b@  }@b@@b@  public static boolean isPrimitive(Type type) {@b@    return ((type instanceof Class) && (((Class)type).isPrimitive()));@b@  }@b@@b@  public static Class<?> classOfType(Type type) {@b@    Type[] ubs;@b@    if (type instanceof Class)@b@      return ((Class)type);@b@    if (type instanceof ParameterizedType)@b@      return ((Class)((ParameterizedType)type).getRawType());@b@    if (type instanceof WildcardType)@b@    {@b@      ubs = ((WildcardType)type).getUpperBounds();@b@      if (ubs.length > 0)@b@        return classOfType(ubs[0]);@b@    }@b@    if (type instanceof GenericArrayType) {@b@      Class ct = classOfType(((GenericArrayType)type).getGenericComponentType());@b@      return ((ct != null) ? Array.newInstance(ct, 0).getClass() : [Ljava.lang.Object.class);@b@    }@b@    if (type instanceof TypeVariable)@b@    {@b@      ubs = ((TypeVariable)type).getBounds();@b@      if (ubs.length > 0)@b@        return classOfType(ubs[0]);@b@    }@b@@b@    return Object.class;@b@  }@b@@b@  public static Type getBoundType(TypeVariable<?> typeVariable) {@b@    Type[] ubs = typeVariable.getBounds();@b@    if (ubs.length > 0) {@b@      return ubs[0];@b@    }@b@@b@    if (typeVariable.getGenericDeclaration() instanceof Type)@b@      return ((Type)typeVariable.getGenericDeclaration());@b@    return typeVariable;@b@  }@b@@b@  public static String getPackageName(Class<?> clazz) {@b@    return ((clazz.getPackage() != null) ? clazz.getPackage().getName() : ""); }@b@@b@  public static PropertyDescriptor[] getProperties(Class<?> clazz) {@b@    PropertyDescriptor[] properties;@b@    try {@b@      properties = Introspector.getBeanInfo(clazz).getPropertyDescriptors();@b@      Field[] fields = clazz.getDeclaredFields();@b@      label159: label249: for (Field field : fields)@b@        if (Boolean.class.equals(field.getType())) {@b@          boolean found = false;@b@          for (PropertyDescriptor property : properties)@b@            if (property.getName().equals(field.getName())) {@b@              found = true;@b@              if (property.getReadMethod() != null) break;@b@              try {@b@                readMethod = clazz.getDeclaredMethod(getIsMethodName(field.getName()), new Class[0]);@b@                if ((!(Modifier.isPublic(readMethod.getModifiers()))) || (Modifier.isStatic(readMethod.getModifiers()))) break label159;@b@                property.setReadMethod(readMethod);@b@              }@b@              catch (NoSuchMethodException readMethod)@b@              {@b@              }@b@              break;@b@            }@b@@b@          if (!(found))@b@            try {@b@              readMethod = clazz.getDeclaredMethod(getIsMethodName(field.getName()), new Class[0]);@b@              if ((!(Modifier.isPublic(readMethod.getModifiers()))) || (Modifier.isStatic(readMethod.getModifiers()))) break label249;@b@              PropertyDescriptor[] propertiesTmp = new PropertyDescriptor[properties.length + 1];@b@              System.arraycopy(properties, 0, propertiesTmp, 0, properties.length);@b@              propertiesTmp[properties.length] = new PropertyDescriptor(field.getName(), readMethod, null);@b@              properties = propertiesTmp;@b@            }@b@            catch (NoSuchMethodException readMethod)@b@            {@b@            }@b@        }@b@@b@@b@      return properties;@b@    } catch (Exception e) {@b@      throw new RuntimeException("Could not introspect properties of class: " + clazz, e);@b@    }@b@  }@b@@b@  private static String getIsMethodName(String name) {@b@    return "is" + name.substring(0, 1).toUpperCase() + name.substring(1);@b@  }@b@@b@  public static ClassLoader getClassLoader(Class<?> clazz) {@b@    return ((clazz.getClassLoader() != null) ? clazz.getClassLoader() : ClassLoader.getSystemClassLoader());@b@  }@b@@b@  public static URL findResource(Class<?> clazz) {@b@    if (clazz.isArray())@b@      clazz = clazz.getComponentType();@b@    if (clazz.isPrimitive())@b@      return null;@b@    URL url = getClassLoader(clazz).getResource(toResourceName(clazz));@b@    String path = url.toString();@b@    if (path.indexOf(32) != -1)@b@      try {@b@        url = new URL(path.replace(" ", "%20"));@b@      }@b@      catch (MalformedURLException localMalformedURLException)@b@      {@b@      }@b@    return url;@b@  }@b@@b@  public static String toResourceName(Class<?> clazz) {@b@    return clazz.getName().replace('.', '/').concat(".class");@b@  }@b@@b@  public static String getMethodSignature(Method method) {@b@    StringBuilder sb = new StringBuilder();@b@    sb.append(method.getName()).append('(');@b@    Class[] params = method.getParameterTypes();@b@    for (int i = 0; i < params.length; ++i) {@b@      if (i > 0)@b@        sb.append(',');@b@      sb.append(getTypeSignature(params[i]));@b@    }@b@    sb.append(')');@b@    return sb.toString();@b@  }@b@@b@  public static String getTypeSignature(Class<?> type) {@b@    if (type.isArray())@b@      try {@b@        dimensions = 1;@b@        Class clazz = type.getComponentType();@b@        while (clazz.isArray()) {@b@          ++dimensions;@b@          clazz = clazz.getComponentType();@b@        }@b@@b@        StringBuffer sb = new StringBuffer(clazz.getName());@b@        while (dimensions-- > 0)@b@          sb.append("[]");@b@        return sb.toString();@b@      }@b@      catch (java.lang.Throwable dimensions)@b@      {@b@      }@b@    return type.getName();@b@  }@b@@b@  public static Method getMethod(Class<?> clazz, String signature) throws NoSuchMethodException {@b@    signature = StringUtil.removeSpaces(signature);@b@@b@    if (!(signature.endsWith(")")))@b@      signature = signature + "()";@b@@b@    for (Method method : clazz.getMethods())@b@      if (signature.equals(getMethodSignature(method)))@b@        return method;@b@@b@@b@    throw new NoSuchMethodException("Could not find method: " + signature + " in class: " + clazz);@b@  }@b@}