當前位置:首頁 > IT技術(shù) > 編程語言 > 正文

Java工具集-類(ClassUtils)
2022-03-06 18:01:11


簡單工具類


寫作初衷:由于日常開發(fā)經(jīng)常需要用到很多工具類,經(jīng)常根據(jù)需求自己寫也比較麻煩
網(wǎng)上好了一些工具類例如commom.lang3或者hutool或者Jodd這樣的開源工具,但是
發(fā)現(xiàn)他們之中雖然設計不錯,但是如果我想要使用,就必須要引入依賴并且去維護依賴,有些
甚至會有存在版本編譯不通過問題,故此想要寫作一個每個類都可以作為獨立工具類使用
每個使用者只需要復制該類,到任何項目當中都可以使用,所以需要尊從以下兩個原則才能
做到.在此誠邀各位大佬參與.可以把各自用過的工具,整合成只依賴JDK,每個類都能夠單獨
使用的工具.每個人當遇到業(yè)務需求需要使用的時候,只需要到這里單獨拷貝一個即可使用.
拋棄傳統(tǒng)的需要引入依賴的煩惱.讓大家一起來解決你所面臨的業(yè)務問題吧!


介紹


遵從兩大原則



  • 1.絕不依賴JDK以外的源碼
  • 2.犧牲代碼復用性,每個類都必須是單獨的組件,絕不互相引用,做到完全解耦

package com.simple.util.base;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
* @program: simple_tools
* @description:
* @author: ChenWenLong
* @create: 2019-05-31 10:43
**/
public class ClassUtils {

public ClassUtils() {
super();
}
//包分割符
public static final char PACKAGE_SEPARATOR_CHAR = '.';
//字符串類型的包分隔符
public static final String PACKAGE_SEPARATOR = String.valueOf(PACKAGE_SEPARATOR_CHAR);
//內(nèi)部類分割符
public static final char INNER_CLASS_SEPARATOR_CHAR = '$';
//字符串類型內(nèi)部類分隔符
public static final String INNER_CLASS_SEPARATOR = String.valueOf(INNER_CLASS_SEPARATOR_CHAR);

//基本類型的Map集合
private static Map primitiveWrapperMap = new HashMap();
static {
primitiveWrapperMap.put(Boolean.TYPE, Boolean.class);
primitiveWrapperMap.put(Byte.TYPE, Byte.class);
primitiveWrapperMap.put(Character.TYPE, Character.class);
primitiveWrapperMap.put(Short.TYPE, Short.class);
primitiveWrapperMap.put(Integer.TYPE, Integer.class);
primitiveWrapperMap.put(Long.TYPE, Long.class);
primitiveWrapperMap.put(Double.TYPE, Double.class);
primitiveWrapperMap.put(Float.TYPE, Float.class);
primitiveWrapperMap.put(Void.TYPE, Void.TYPE);
}

//用于交換的Map類型集合
private static Map wrapperPrimitiveMap = new HashMap();
static {
for (Iterator it = primitiveWrapperMap.keySet().iterator(); it.hasNext();) {
Class primitiveClass = (Class) it.next();
Class wrapperClass = (Class) primitiveWrapperMap.get(primitiveClass);
if (!primitiveClass.equals(wrapperClass)) {
wrapperPrimitiveMap.put(wrapperClass, primitiveClass);
}
}
}
//用于存儲類型名稱簡寫的Map
private static Map abbreviationMap = new HashMap();
//類名縮寫的替換Map集合
private static Map reverseAbbreviationMap = new HashMap();

/**
* 功能描述:
* 〈基本類型的類名縮寫添加到Map當中〉
*
* @params : [primitive, abbreviation]
* @return : void
* @author : cwl
* @date : 2019/5/31 15:22
*/
private static void addAbbreviation(String primitive, String abbreviation) {
abbreviationMap.put(primitive, abbreviation);
reverseAbbreviationMap.put(abbreviation, primitive);
}

/**
* 功能描述:
* 〈將類型縮寫對應的添加到Map當中〉
*
* @params :
* @return :
* @author : cwl
* @date : 2019/5/31 15:23
*/
static {
addAbbreviation("int", "I");
addAbbreviation("boolean", "Z");
addAbbreviation("float", "F");
addAbbreviation("long", "J");
addAbbreviation("short", "S");
addAbbreviation("byte", "B");
addAbbreviation("double", "D");
addAbbreviation("char", "C");
}

/**
* 功能描述:
* 〈獲取object的名臣簡寫,valueIfNull為當object==null時返回的默認參數(shù)〉
*
* @params : [object, valueIfNull]
* @return : java.lang.String
* @author : cwl
* @date : 2019/5/31 15:27
*/
public static String getShortClassName(Object object, String valueIfNull) {
if (object == null) {
return valueIfNull;
}
return getShortClassName(object.getClass().getName());
}

/**
* 功能描述:
* 〈根據(jù)cls對象獲取它的簡單類型名稱〉
*
* @params : [cls]
* @return : java.lang.String
* @author : cwl
* @date : 2019/5/31 15:32
*/
public static String getShortClassName(Class cls) {
if (cls == null) {
return "";
}
return getShortClassName(cls.getName());
}

/**
* 功能描述:
* 〈依據(jù)字符串className名稱獲取它的簡寫字符名稱〉
*
* @params : [className]
* @return : java.lang.String
* @author : cwl
* @date : 2019/5/31 15:33
*/
private static String getShortClassName(String className) {
if (className == null) {
return "";
}
if (className.length() == 0) {
return "";
}

int lastDotIdx = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
int innerIdx = className.indexOf(
INNER_CLASS_SEPARATOR_CHAR, lastDotIdx == -1 ? 0 : lastDotIdx + 1);
String out = className.substring(lastDotIdx + 1);
if (innerIdx != -1) {
out = out.replace(INNER_CLASS_SEPARATOR_CHAR, PACKAGE_SEPARATOR_CHAR);
}
return out;
}

/**
* 功能描述:
* 〈獲取object對象所在的包名稱,valueIfNull是當object為null時返回的默認值〉
*
* @params : [object, valueIfNull]
* @return : java.lang.String
* @author : cwl
* @date : 2019/5/31 15:34
*/
public static String getPackageName(Object object, String valueIfNull) {
if (object == null) {
return valueIfNull;
}
return getPackageName(object.getClass().getName());
}

/**
* 功能描述:
* 〈根據(jù)字節(jié)碼對象cls獲取該對象所在包名稱〉
*
* @params : [cls]
* @return : java.lang.String
* @author : cwl
* @date : 2019/5/31 15:35
*/
public static String getPackageName(Class cls) {
if (cls == null) {
return "";
}
return getPackageName(cls.getName());
}

/**
* 功能描述:
* 〈根據(jù)className獲得它所在的報名〉
*
* @params : [className]
* @return : java.lang.String
* @author : cwl
* @date : 2019/5/31 15:36
*/
private static String getPackageName(String className) {
if (className == null) {
return "";
}
int i = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
if (i == -1) {
return "";
}
return className.substring(0, i);
}

/**
* 功能描述:
* 〈獲取cls所有的父類對象〉
*
* @params : [cls]
* @return : java.util.List
* @author : cwl
* @date : 2019/5/31 15:38
*/
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;
}

/**
* 功能描述:
* 〈獲取cls對象所有實現(xiàn)的接口〉
*
* @params : [cls]
* @return : java.util.List
* @author : cwl
* @date : 2019/5/31 15:39
*/
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;
}

/**
* 功能描述:
* 〈將類名轉(zhuǎn)換成為Class對象,貌似也沒啥用處〉
*
* @params : [classNames]
* @return : java.util.List<java.lang.Class>
* @author : cwl
* @date : 2019/5/31 15:52
*/
public static List convertClassNamesToClasses(List<String> 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;
}

/**
* 功能描述:
* 〈classes集合轉(zhuǎn)換成為全限定類名的集合〉
*
* @params : [classes]
* @return : java.util.List
* @author : cwl
* @date : 2019/5/31 16:01
*/
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;
}

/**
* 功能描述:
* 〈判斷classArray數(shù)組能否轉(zhuǎn)換為toClassArray〉
*
* @params : [classArray, toClassArray]
* @return : boolean
* @author : cwl
* @date : 2019/5/31 16:58
*/
public static boolean isAssignable(Class[] classArray, Class[] toClassArray) {
if ((classArray == null && toClassArray != null && toClassArray.length > 0) ||
(toClassArray == null && classArray != null && classArray.length > 0) ||
(classArray != null && toClassArray != null && classArray.length != toClassArray.length)) {
return false;
}
if (classArray == null) {
classArray = new Class[0];
}
if (toClassArray == null) {
toClassArray = new Class[0];
}
for (int i = 0; i < classArray.length; i++) {
if (isAssignable(classArray[i], toClassArray[i]) == false) {
return false;
}
}
return true;
}

/**
* 功能描述:
* 〈判斷cls能否轉(zhuǎn)換為toClass〉
*
* @params : [cls, toClass]
* @return : boolean
* @author : cwl
* @date : 2019/5/31 16:59
*/
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);
}

/**
* 功能描述:
* 〈類名轉(zhuǎn)全限定類名〉
*
* @params : [cls]
* @return : java.lang.Class
* @author : cwl
* @date : 2019/5/31 17:07
*/
public static Class primitiveToWrapper(Class cls) {
Class convertedClass = cls;
if (cls != null && cls.isPrimitive()) {
convertedClass = (Class) primitiveWrapperMap.get(cls);
}
return convertedClass;
}

/**
* 功能描述:
* 〈類名數(shù)組轉(zhuǎn)全限定類名數(shù)組〉
*
* @params : [classes]
* @return : java.lang.Class[]
* @author : cwl
* @date : 2019/5/31 17:08
*/
public static Class[] primitivesToWrappers(Class[] classes) {
if (classes == null) {
return null;
}

if (classes.length == 0) {
return classes;
}

Class[] convertedClasses = new Class[classes.length];
for (int i=0; i < classes.length; i++) {
convertedClasses[i] = primitiveToWrapper( classes[i] );
}
return convertedClasses;
}

/**
* 功能描述:
* 〈全限定類名轉(zhuǎn)類名〉
*
* @params : [cls]
* @return : java.lang.Class
* @author : cwl
* @date : 2019/5/31 17:45
*/
public static Class wrapperToPrimitive(Class cls) {
return (Class) wrapperPrimitiveMap.get(cls);
}

/**
* 功能描述:
* 〈全限定類名數(shù)組轉(zhuǎn)類名數(shù)組〉
*
* @params : [classes]
* @return : java.lang.Class[]
* @author : cwl
* @date : 2019/5/31 17:45
*/
public static Class[] wrappersToPrimitives(Class[] classes) {
if (classes == null) {
return null;
}

if (classes.length == 0) {
return classes;
}

Class[] convertedClasses = new Class[classes.length];
for (int i=0; i < classes.length; i++) {
convertedClasses[i] = wrapperToPrimitive( classes[i] );
}
return convertedClasses;
}

/**
* 功能描述:
* 〈是否是內(nèi)部類〉
*
* @params : [cls]
* @return : boolean
* @author : cwl
* @date : 2019/5/31 17:45
*/
public static boolean isInnerClass(Class cls) {
if (cls == null) {
return false;
}
return cls.getName().indexOf(INNER_CLASS_SEPARATOR_CHAR) >= 0;
}

/**
* 功能描述:
* 〈從類加載器當中獲取字節(jié)碼對象〉
*
* @params : [classLoader, className, initialize]
* @return : java.lang.Class
* @author : cwl
* @date : 2019/5/31 17:46
*/
public static Class getClass(
ClassLoader classLoader, String className, boolean initialize) throws ClassNotFoundException {
Class clazz;
if (abbreviationMap.containsKey(className)) {
String clsName = "[" + abbreviationMap.get(className);
clazz = Class.forName(clsName, initialize, classLoader).getComponentType();
} else {
clazz = Class.forName(toCanonicalName(className), initialize, classLoader);
}
return clazz;
}

/**
* 功能描述:
* 〈從類加載器當中獲取字節(jié)碼對象〉
*
* @params : [classLoader, className]
* @return : java.lang.Class
* @author : cwl
* @date : 2019/5/31 17:47
*/
public static Class getClass(ClassLoader classLoader, String className) throws ClassNotFoundException {
return getClass(classLoader, className, true);
}

/**
* 功能描述:
* 〈根據(jù)className獲取字節(jié)碼對象〉
*
* @params : [className]
* @return : java.lang.Class
* @author : cwl
* @date : 2019/5/31 17:47
*/
private static Class getClass(String className) throws ClassNotFoundException {
return getClass(className, true);
}

/**
* 功能描述:
* 〈根據(jù)className獲取字節(jié)碼對象〉
*
* @params : [className, initialize]
* @return : java.lang.Class
* @author : cwl
* @date : 2019/5/31 17:48
*/
private static Class getClass(String className, boolean initialize) throws ClassNotFoundException {
ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
ClassLoader loader = contextCL == null ? ClassUtils.class.getClassLoader() : contextCL;
return getClass(loader, className, initialize );
}

/**
* 功能描述:
* 〈獲取cls的公共方法〉
*
* @params : [cls, methodName, parameterTypes]
* @return : java.lang.reflect.Method
* @author : cwl
* @date : 2019/5/31 17:49
*/
public static Method getPublicMethod(Class cls, String methodName, Class parameterTypes[])
throws SecurityException, NoSuchMethodException {

Method declaredMethod = cls.getMethod(methodName, parameterTypes);
if (Modifier.isPublic(declaredMethod.getDeclaringClass().getModifiers())) {
return declaredMethod;
}

List candidateClasses = new ArrayList();
candidateClasses.addAll(getAllInterfaces(cls));
candidateClasses.addAll(getAllSuperclasses(cls));

for (Iterator it = candidateClasses.iterator(); it.hasNext(); ) {
Class candidateClass = (Class) it.next();
if (!Modifier.isPublic(candidateClass.getModifiers())) {
continue;
}
Method candidateMethod;
try {
candidateMethod = candidateClass.getMethod(methodName, parameterTypes);
} catch (NoSuchMethodException ex) {
continue;
}
if (Modifier.isPublic(candidateMethod.getDeclaringClass().getModifiers())) {
return candidateMethod;
}
}

throw new NoSuchMethodException("Can't find a public method for " +
methodName);
}

/**
* 功能描述:
* 〈轉(zhuǎn)換成JSL規(guī)范的類名〉
*
* @params : [className]
* @return : java.lang.String
* @author : cwl
* @date : 2019/5/31 17:52
*/
private static String toCanonicalName(String className) {
className = StringUtils.deleteWhitespace(className);
if (className == null) {
throw new NullPointerException("className is null");
} else if (className.endsWith("[]")) {
StringBuffer classNameBuffer = new StringBuffer();
while (className.endsWith("[]")) {
className = className.substring(0, className.length() - 2);
classNameBuffer.append("[");
}
String abbreviation = (String) abbreviationMap.get(className);
if (abbreviation != null) {
classNameBuffer.append(abbreviation);
} else {
classNameBuffer.append("L").append(className).append(";");
}
className = classNameBuffer.toString();
}
return className;
}

/**
* 功能描述:
* 〈Object類型的數(shù)組array轉(zhuǎn)換成它對應的字節(jié)碼對象〉
*
* @params : [array]
* @return : java.lang.Class[]
* @author : cwl
* @date : 2019/5/31 17:53
*/
public static Class[] toClass(Object[] array)
{
if (array == null) {
return null;
} else if (array.length == 0) {
return new Class[0];
}
Class[] classes = new Class[array.length];
for (int i = 0; i < array.length; i++) {
classes[i] = array[i].getClass();
}
return classes;
}

/**
* 功能描述:
* 〈獲取object對象的簡稱,valueIfNull為當object為null時的返回值〉
*
* @params : [object, valueIfNull]
* @return : java.lang.String
* @author : cwl
* @date : 2019/5/31 17:53
*/
public static String getShortCanonicalName(Object object, String valueIfNull) {
if (object == null) {
return valueIfNull;
}
return getShortCanonicalName(object.getClass().getName());
}

/**
* 功能描述:
* 〈獲取cls字節(jié)碼對象的簡稱〉
*
* @params : [cls]
* @return : java.lang.String
* @author : cwl
* @date : 2019/5/31 17:55
*/
public static String getShortCanonicalName(Class cls) {
if (cls == null) {
return "";
}
return getShortCanonicalName(cls.getName());
}

/**
* 功能描述:
* 〈獲取canonicalName的簡稱〉
*
* @params : [canonicalName]
* @return : java.lang.String
* @author : cwl
* @date : 2019/5/31 17:55
*/
public static String getShortCanonicalName(String canonicalName) {
return ClassUtils.getShortClassName(getCanonicalName(canonicalName));
}

/**
* 功能描述:
* 〈獲取canonicalName的簡稱〉
*
* @params : [className]
* @return : java.lang.String
* @author : cwl
* @date : 2019/5/31 17:58
*/
private static String getCanonicalName(String className) {
className = StringUtils.deleteWhitespace(className);
if (className == null) {
return null;
} else {
int dim = 0;
while(className.startsWith("[")) {
dim++;
className = className.substring(1);
}
if(dim < 1) {
return className;
} else {
if(className.startsWith("L")) {
className = className.substring(
1,
className.endsWith(";")
? className.length() - 1
: className.length());
} else {
if(className.length() > 0) {
className = (String) reverseAbbreviationMap.get(
className.substring(0, 1));
}
}
StringBuffer canonicalClassNameBuffer = new StringBuffer(className);
for(int i = 0; i < dim; i++) {
canonicalClassNameBuffer.append("[]");
}
return canonicalClassNameBuffer.toString();
}
}
}
}



本文摘自 :https://blog.51cto.com/u

開通會員,享受整站包年服務立即開通 >