ClassKit.java 32.8 KB
Newer Older
S
smallchill 已提交
1
package org.springblade.core.toolbox.kit;
Z
zhuangqian 已提交
2

3 4 5 6 7 8 9 10
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springblade.core.exception.ToolBoxException;
import org.springblade.core.toolbox.support.BasicType;
import org.springblade.core.toolbox.support.Singleton;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;

Z
zhuangqian 已提交
11 12 13 14
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.lang.annotation.Annotation;
15
import java.lang.reflect.*;
Z
zhuangqian 已提交
16
import java.net.URI;
Z
zhuangqian 已提交
17
import java.net.URL;
18
import java.util.*;
Z
zhuangqian 已提交
19 20 21 22 23 24 25 26 27 28 29
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * 类工具类
 * 1、扫描指定包下的所有类<br>
 * 参考 http://www.oschina.net/code/snippet_234657_22722
 * @author seaside_hi, xiaoleilu, chill
 *
 */
public class ClassKit {
30
	private final static Logger log = LogManager.getLogger(ClassKit.class);
Z
zhuangqian 已提交
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
	
	private ClassKit() {
		// 静态类不可实例化
	}
	
	/**
	 * 获得对象数组的类数组
	 * @param objects 对象数组
	 * @return 类数组
	 */
	public static Class<?>[] getClasses(Object... objects){
		Class<?>[] classes = new Class<?>[objects.length];
		for (int i = 0; i < objects.length; i++) {
			classes[i] = objects[i].getClass();
		}
		return classes;
	}
	
	/**
	 * 获得泛型的第一个类
	 * @param clazz 当前类
	 * @return 泛型类
	 */
	@SuppressWarnings("rawtypes")
	public static Class getSuperClassGenricFirstType(Class clazz){
		return getSuperClassGenricType(clazz, 0);
	}
	
	/**
	 * 获得泛型的类
	 * @param clazz 当前类
	 * @param index 泛型顺序
	 * @return 泛型类
	 */
	@SuppressWarnings("rawtypes")
	public static Class getSuperClassGenricType(Class clazz, int index){
		Type t = clazz.getGenericSuperclass();
		if (!(t instanceof ParameterizedType)) {
			return null;
		}
		ParameterizedType parameterizedType = (ParameterizedType) t;
		Type[] params = parameterizedType.getActualTypeArguments();
		if (null == params) {
			return null;
		}
		if (index < 0 || index > params.length - 1) {
			return null;
		}
Z
bug fix  
zhuangqian 已提交
79
		Type param = params[index];
Z
zhuangqian 已提交
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
		if (param instanceof Class) {
			return (Class) param;
		}
		return null;
	}
	
	/**
	 * 扫面该包路径下所有class文件
	 * 
	 * @return 类集合
	 */
	public static Set<Class<?>> scanPackage() {
		return scanPackage(StrKit.EMPTY, null);
	}
	
	/**
	 * 扫面该包路径下所有class文件
	 * 
	 * @param packageName 包路径 com | com. | com.abs | com.abs.
	 * @return 类集合
	 */
	public static Set<Class<?>> scanPackage(String packageName) {
		return scanPackage(packageName, null);
	}
	
	/**
	 * 扫描指定包路径下所有包含指定注解的类
	 * @param packageName 包路径
	 * @param annotationClass 注解类
	 * @return 类集合
	 */
	public static Set<Class<?>> scanPackageByAnnotation(String packageName, final Class<? extends Annotation> annotationClass) {
		return scanPackage(packageName, new ClassFilter() {
			@Override
			public boolean accept(Class<?> clazz) {
				return clazz.isAnnotationPresent(annotationClass);
			}
		});
	}
	
	/**
	 * 扫描指定包路径下所有指定类的子类
	 * @param packageName 包路径
	 * @param superClass 父类 
	 * @return 类集合
	 */
	public static Set<Class<?>> scanPackageBySuper(String packageName, final Class<?> superClass) {
		return scanPackage(packageName, new ClassFilter() {
			@Override
			public boolean accept(Class<?> clazz) {
				return superClass.isAssignableFrom(clazz) && !superClass.equals(clazz);
			}
		});
	}
	
	/**
	 * 扫面包路径下满足class过滤器条件的所有class文件,</br> 
	 * 如果包路径为 com.abs + A.class 但是输入 abs会产生classNotFoundException</br>
	 * 因为className 应该为 com.abs.A 现在却成为abs.A,此工具类对该异常进行忽略处理,有可能是一个不完善的地方,以后需要进行修改</br>
	 * 
	 * @param packageName 包路径 com | com. | com.abs | com.abs.
	 * @param classFilter class过滤器,过滤掉不需要的class
	 * @return 类集合
	 */
	public static Set<Class<?>> scanPackage(String packageName, ClassFilter classFilter) {
		if(StrKit.isBlank(packageName)) {
			packageName = StrKit.EMPTY;
		}
		log.debug("Scan classes from package ["+packageName+"]...");
		packageName = getWellFormedPackageName(packageName);
		
		final Set<Class<?>> classes = new HashSet<Class<?>>();
		for (String classPath : getClassPaths(packageName)) {
			//bug修复,由于路径中空格和中文导致的Jar找不到
			classPath = URLKit.decode(classPath, CharsetKit.systemCharset());
			log.debug("Scan classpath: ["+classPath+"]");
			// 填充 classes
			fillClasses(classPath, packageName, classFilter, classes);
		}
		
		//如果在项目的ClassPath中未找到,去系统定义的ClassPath里找
		if(classes.isEmpty()) {
			for (String classPath : getJavaClassPaths()) {
				//bug修复,由于路径中空格和中文导致的Jar找不到
				classPath = URLKit.decode(classPath, CharsetKit.systemCharset());
				
				log.debug("Scan java classpath: ["+classPath+"]");
				// 填充 classes
				fillClasses(classPath, new File(classPath), packageName, classFilter, classes);
			}
		}
		return classes;
	}
Z
zhuangqian 已提交
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
	
	// ----------------------------------------------------------------------------------------- Method
	
	/**
	 * 获得指定类中的Public方法名<br>
	 * 去重重载的方法
	 * 
	 * @param clazz 类
	 */
	public static Set<String> getPublicMethodNames(Class<?> clazz) {
		HashSet<String> methodSet = new HashSet<String>();
		Method[] methodArray = getPublicMethods(clazz);
		for (Method method : methodArray) {
			String methodName = method.getName();
			methodSet.add(methodName);
		}
		return methodSet;
	}

	/**
	 * 获得本类及其父类所有Public方法
	 * 
	 * @param clazz 查找方法的类
	 * @return 过滤后的方法列表
	 */
	public static Method[] getPublicMethods(Class<?> clazz) {
		return clazz.getMethods();
	}

	/**
	 * 获得指定类过滤后的Public方法列表
	 * 
	 * @param clazz 查找方法的类
	 * @param filter 过滤器
	 * @return 过滤后的方法列表
	 */
	public static List<Method> getPublicMethods(Class<?> clazz, Filter<Method> filter) {
		if (null == clazz) {
			return null;
		}

		Method[] methods = getPublicMethods(clazz);
		List<Method> methodList;
		if (null != filter) {
			methodList = new ArrayList<>();
			Method filteredMethod;
			for (Method method : methods) {
				filteredMethod = filter.modify(method);
				if (null != filteredMethod) {
					methodList.add(method);
				}
			}
		} else {
			methodList = CollectionKit.newArrayList(methods);
		}
		return methodList;
	}

	/**
	 * 获得指定类过滤后的Public方法列表
	 * 
	 * @param clazz 查找方法的类
	 * @param excludeMethods 不包括的方法
	 * @return 过滤后的方法列表
	 */
	public static List<Method> getPublicMethods(Class<?> clazz, Method... excludeMethods) {
		final HashSet<Method> excludeMethodSet = CollectionKit.newHashSet(excludeMethods);
		Filter<Method> filter = new Filter<Method>(){
			@Override
			public Method modify(Method method) {
				return excludeMethodSet.contains(method) ? null : method;
			}
		};

		return getPublicMethods(clazz, filter);
	}

	/**
	 * 获得指定类过滤后的Public方法列表
	 * 
	 * @param clazz 查找方法的类
	 * @param excludeMethodNames 不包括的方法名列表
	 * @return 过滤后的方法列表
	 */
	public static List<Method> getPublicMethods(Class<?> clazz, String... excludeMethodNames) {
		final HashSet<String> excludeMethodNameSet = CollectionKit.newHashSet(excludeMethodNames);
		Filter<Method> filter = new Filter<Method>(){
			@Override
			public Method modify(Method method) {
				return excludeMethodNameSet.contains(method.getName()) ? null : method;
			}
		};

		return getPublicMethods(clazz, filter);
	}

	/**
	 * 查找指定Public方法
	 * 
	 * @param clazz 类
	 * @param methodName 方法名
	 * @param paramTypes 参数类型
	 * @return 方法
	 * @throws SecurityException
	 * @throws NoSuchMethodException
	 */
	public static Method getPublicMethod(Class<?> clazz, String methodName, Class<?>... paramTypes) throws NoSuchMethodException, SecurityException {
		try {
			return clazz.getMethod(methodName, paramTypes);
		} catch (NoSuchMethodException ex) {
			return getDeclaredMethod(clazz, methodName, paramTypes);
		}
	}
Z
zhuangqian 已提交
286 287 288 289

	/**
	 * 获得指定类中的Public方法名<br>
	 * 去重重载的方法
Z
zhuangqian 已提交
290
	 * 
Z
zhuangqian 已提交
291 292
	 * @param clazz 类
	 */
Z
zhuangqian 已提交
293
	public static Set<String> getDeclaredMethodNames(Class<?> clazz) {
Z
zhuangqian 已提交
294
		HashSet<String> methodSet = new HashSet<String>();
Z
zhuangqian 已提交
295
		Method[] methodArray = getDeclaredMethods(clazz);
Z
zhuangqian 已提交
296 297 298 299 300 301
		for (Method method : methodArray) {
			String methodName = method.getName();
			methodSet.add(methodName);
		}
		return methodSet;
	}
Z
zhuangqian 已提交
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392

	/**
	 * 获得声明的所有方法,包括本类及其父类和接口的所有方法和Object类的方法
	 * 
	 * @param clazz 类
	 * @return 方法数组
	 */
	public static Method[] getDeclaredMethods(Class<?> clazz) {
		Set<Method> methodSet = new HashSet<>();
		Method[] declaredMethods;
		for (; null != clazz; clazz = clazz.getSuperclass()) {
			declaredMethods = clazz.getDeclaredMethods();
			for (Method method : declaredMethods) {
				methodSet.add(method);
			}
		}
		return methodSet.toArray(new Method[methodSet.size()]);
	}

	/**
	 * 查找指定对象中的所有方法(包括非public方法),也包括父对象和Object类的方法
	 * 
	 * @param obj 被查找的对象
	 * @param methodName 方法名
	 * @param args 参数
	 * @return 方法
	 * @throws NoSuchMethodException 无此方法
	 * @throws SecurityException
	 */
	public static Method getDeclaredMethod(Object obj, String methodName, Object... args) throws NoSuchMethodException, SecurityException {
		return getDeclaredMethod(obj.getClass(), methodName, getClasses(args));
	}

	/**
	 * 查找指定类中的所有方法(包括非public方法),也包括父类和Object类的方法
	 * 
	 * @param clazz 被查找的类
	 * @param methodName 方法名
	 * @param parameterTypes 参数类型
	 * @return 方法
	 * @throws NoSuchMethodException 无此方法
	 * @throws SecurityException
	 */
	public static Method getDeclaredMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) throws NoSuchMethodException, SecurityException {
		Method method = null;
		for (; null != clazz; clazz = clazz.getSuperclass()) {
			try {
				method = clazz.getDeclaredMethod(methodName, parameterTypes);
				break;
			} catch (NoSuchMethodException e) {
				// 继续向上寻找
			}
		}
		return method;
	}

	/**
	 * 是否为equals方法
	 * 
	 * @param method 方法
	 * @return 是否为equals方法
	 */
	public static boolean isEqualsMethod(Method method) {
		if (method == null || !method.getName().equals("equals")) {
			return false;
		}
		Class<?>[] paramTypes = method.getParameterTypes();
		return (paramTypes.length == 1 && paramTypes[0] == Object.class);
	}

	/**
	 * 是否为hashCode方法
	 * 
	 * @param method 方法
	 * @return 是否为hashCode方法
	 */
	public static boolean isHashCodeMethod(Method method) {
		return (method != null && method.getName().equals("hashCode") && method.getParameterTypes().length == 0);
	}

	/**
	 * 是否为toString方法
	 * 
	 * @param method 方法
	 * @return 是否为toString方法
	 */
	public static boolean isToStringMethod(Method method) {
		return (method != null && method.getName().equals("toString") && method.getParameterTypes().length == 0);
	}

	// ----------------------------------------------------------------------------------------- Classpath
Z
zhuangqian 已提交
393
	
Z
zhuangqian 已提交
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
	/**
	 * 获得ClassPath
	 * 
	 * @return ClassPath集合
	 */
	public static Set<String> getClassPathResources() {
		return getClassPaths(StrKit.EMPTY);
	}

	/**
	 * 获得ClassPath
	 * 
	 * @param packageName 包名称
	 * @return ClassPath路径字符串集合
	 */
	public static Set<String> getClassPaths(String packageName) {
		String packagePath = packageName.replace(StrKit.DOT, StrKit.SLASH);
		Enumeration<URL> resources;
		try {
			resources = getClassLoader().getResources(packagePath);
		} catch (IOException e) {
			throw new ToolBoxException(StrKit.format("Loading classPath [{}] error!", packagePath), e);
		}
		Set<String> paths = new HashSet<String>();
		while (resources.hasMoreElements()) {
			paths.add(resources.nextElement().getPath());
		}
		return paths;
	}

	/**
	 * 获得ClassPath
	 * 
	 * @return ClassPath
	 */
	public static String getClassPath() {
		return getClassPathURL().getPath();
	}

	/**
	 * 获得ClassPath URL
	 * 
	 * @return ClassPath URL
	 */
	public static URL getClassPathURL() {
		return getURL(StrKit.EMPTY);
	}

	/**
	 * 获得资源的URL
	 * 
	 * @param resource 资源(相对Classpath的路径)
	 * @return 资源URL
	 */
	public static URL getURL(String resource) {
		return ClassKit.getClassLoader().getResource(resource);
	}

Z
zhuangqian 已提交
452 453 454 455 456 457 458
	/**
	 * @return 获得Java ClassPath路径,不包括 jre
	 */
	public static String[] getJavaClassPaths() {
		String[] classPaths = System.getProperty("java.class.path").split(System.getProperty("path.separator"));
		return classPaths;
	}
Z
zhuangqian 已提交
459

Z
zhuangqian 已提交
460
	/**
Z
zhuangqian 已提交
461 462 463
	 * 转换为原始类型
	 * 
	 * @param clazz 被转换为原始类型的类,必须为包装类型的类
Z
zhuangqian 已提交
464 465 466
	 * @return 基本类型类
	 */
	public static Class<?> castToPrimitive(Class<?> clazz) {
Z
zhuangqian 已提交
467
		if (null == clazz || clazz.isPrimitive()) {
Z
zhuangqian 已提交
468 469
			return clazz;
		}
Z
zhuangqian 已提交
470

Z
zhuangqian 已提交
471 472 473
		BasicType basicType;
		try {
			basicType = BasicType.valueOf(clazz.getSimpleName().toUpperCase());
Z
zhuangqian 已提交
474
		} catch (Exception e) {
Z
zhuangqian 已提交
475 476
			return clazz;
		}
Z
zhuangqian 已提交
477 478

		// 基本类型
Z
zhuangqian 已提交
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
		switch (basicType) {
			case BYTE:
				return byte.class;
			case SHORT:
				return short.class;
			case INTEGER:
				return int.class;
			case LONG:
				return long.class;
			case DOUBLE:
				return double.class;
			case FLOAT:
				return float.class;
			case BOOLEAN:
				return boolean.class;
			case CHAR:
				return char.class;
			default:
				return clazz;
		}
	}
Z
zhuangqian 已提交
500

Z
zhuangqian 已提交
501 502 503 504 505 506
	/**
	 * @return 当前线程的class loader
	 */
	public static ClassLoader getContextClassLoader() {
		return Thread.currentThread().getContextClassLoader();
	}
Z
zhuangqian 已提交
507

Z
zhuangqian 已提交
508 509 510
	/**
	 * 获得class loader<br>
	 * 若当前线程class loader不存在,取当前类的class loader
Z
zhuangqian 已提交
511
	 * 
Z
zhuangqian 已提交
512 513 514 515
	 * @return 类加载器
	 */
	public static ClassLoader getClassLoader() {
		ClassLoader classLoader = getContextClassLoader();
Z
zhuangqian 已提交
516
		if (classLoader == null) {
Z
zhuangqian 已提交
517 518 519 520 521 522 523
			classLoader = ClassKit.class.getClassLoader();
		}
		return classLoader;
	}

	/**
	 * 实例化对象
Z
zhuangqian 已提交
524
	 * 
Z
zhuangqian 已提交
525 526 527 528 529
	 * @param clazz 类名
	 * @return 对象
	 */
	@SuppressWarnings("unchecked")
	public static <T> T newInstance(String clazz) {
530 531 532
		if (null == clazz) {
            return null;
        }
Z
zhuangqian 已提交
533 534 535 536 537 538
		try {
			return (T) Class.forName(clazz).newInstance();
		} catch (Exception e) {
			throw new ToolBoxException(StrKit.format("Instance class [{}] error!", clazz), e);
		}
	}
Z
zhuangqian 已提交
539

Z
zhuangqian 已提交
540 541
	/**
	 * 实例化对象
Z
zhuangqian 已提交
542
	 * 
Z
zhuangqian 已提交
543 544 545 546
	 * @param clazz 类
	 * @return 对象
	 */
	public static <T> T newInstance(Class<T> clazz) {
547 548 549
		if (null == clazz) {
            return null;
        }
Z
zhuangqian 已提交
550 551 552 553 554 555
		try {
			return (T) clazz.newInstance();
		} catch (Exception e) {
			throw new ToolBoxException(StrKit.format("Instance class [{}] error!", clazz), e);
		}
	}
Z
zhuangqian 已提交
556

Z
zhuangqian 已提交
557 558
	/**
	 * 实例化对象
Z
zhuangqian 已提交
559
	 * 
Z
zhuangqian 已提交
560 561 562 563
	 * @param clazz 类
	 * @return 对象
	 */
	public static <T> T newInstance(Class<T> clazz, Object... params) {
564 565 566
		if (null == clazz) {
            return null;
        }
Z
zhuangqian 已提交
567
		if (CollectionKit.isEmpty(params)) {
Z
zhuangqian 已提交
568 569 570 571 572 573 574 575 576 577 578
			return newInstance(clazz);
		}
		try {
			return clazz.getDeclaredConstructor(getClasses(params)).newInstance(params);
		} catch (Exception e) {
			throw new ToolBoxException(StrKit.format("Instance class [{}] error!", clazz), e);
		}
	}

	/**
	 * 加载类
Z
zhuangqian 已提交
579
	 * 
Z
zhuangqian 已提交
580 581 582 583 584 585 586 587 588 589
	 * @param <T>
	 * @param className 类名
	 * @param isInitialized 是否初始化
	 * @return 类
	 */
	@SuppressWarnings("unchecked")
	public static <T> Class<T> loadClass(String className, boolean isInitialized) {
		Class<T> clazz;
		try {
			clazz = (Class<T>) Class.forName(className, isInitialized, getClassLoader());
Z
zhuangqian 已提交
590
		} catch (ClassNotFoundException e) {
Z
zhuangqian 已提交
591 592 593 594
			throw new ToolBoxException(e);
		}
		return clazz;
	}
Z
zhuangqian 已提交
595

Z
zhuangqian 已提交
596 597
	/**
	 * 加载类并初始化
Z
zhuangqian 已提交
598
	 * 
Z
zhuangqian 已提交
599
	 * @param <T>
Z
zhuangqian 已提交
600
	 * @param className 类名
Z
zhuangqian 已提交
601 602 603 604 605
	 * @return 类
	 */
	public static <T> Class<T> loadClass(String className) {
		return loadClass(className, true);
	}
Z
zhuangqian 已提交
606

Z
zhuangqian 已提交
607
	// ---------------------------------------------------------------------------------------------------- Invoke start
Z
zhuangqian 已提交
608 609 610 611 612
	/**
	 * 执行方法<br>
	 * 可执行Private方法,也可执行static方法<br>
	 * 执行非static方法时,必须满足对象有默认构造方法<br>
	 * 非单例模式,如果是非静态方法,每次创建一个新对象
Z
zhuangqian 已提交
613
	 * 
Z
zhuangqian 已提交
614
	 * @param <T>
Z
zhuangqian 已提交
615
	 * @param classNameDotMethodName 类名和方法名表达式,例如:com.xiaoleilu.hutool.StrKit.isEmpty
Z
zhuangqian 已提交
616 617 618
	 * @param args 参数,必须严格对应指定方法的参数类型和数量
	 * @return 返回结果
	 */
Z
zhuangqian 已提交
619
	public static <T> T invoke(String classNameDotMethodName, Object[] args) {
Z
zhuangqian 已提交
620 621
		return invoke(classNameDotMethodName, false, args);
	}
Z
zhuangqian 已提交
622

Z
zhuangqian 已提交
623 624 625 626
	/**
	 * 执行方法<br>
	 * 可执行Private方法,也可执行static方法<br>
	 * 执行非static方法时,必须满足对象有默认构造方法<br>
Z
zhuangqian 已提交
627
	 * 
Z
zhuangqian 已提交
628
	 * @param <T>
Z
zhuangqian 已提交
629
	 * @param classNameDotMethodName 类名和方法名表达式,例如:com.xiaoleilu.hutool.StrKit.isEmpty
Z
zhuangqian 已提交
630 631 632 633
	 * @param isSingleton 是否为单例对象,如果此参数为false,每次执行方法时创建一个新对象
	 * @param args 参数,必须严格对应指定方法的参数类型和数量
	 * @return 返回结果
	 */
Z
zhuangqian 已提交
634
	public static <T> T invoke(String classNameDotMethodName, boolean isSingleton, Object[] args) {
Z
zhuangqian 已提交
635
		if (StrKit.isBlank(classNameDotMethodName)) {
Z
zhuangqian 已提交
636 637 638
			throw new ToolBoxException("Blank classNameDotMethodName!");
		}
		final int dotIndex = classNameDotMethodName.lastIndexOf('.');
Z
zhuangqian 已提交
639
		if (dotIndex <= 0) {
Z
zhuangqian 已提交
640 641
			throw new ToolBoxException("Invalid classNameDotMethodName [{}]!", classNameDotMethodName);
		}
Z
zhuangqian 已提交
642

Z
zhuangqian 已提交
643 644
		final String className = classNameDotMethodName.substring(0, dotIndex);
		final String methodName = classNameDotMethodName.substring(dotIndex + 1);
Z
zhuangqian 已提交
645

Z
zhuangqian 已提交
646 647
		return invoke(className, methodName, isSingleton, args);
	}
Z
zhuangqian 已提交
648

Z
zhuangqian 已提交
649 650 651 652 653
	/**
	 * 执行方法<br>
	 * 可执行Private方法,也可执行static方法<br>
	 * 执行非static方法时,必须满足对象有默认构造方法<br>
	 * 非单例模式,如果是非静态方法,每次创建一个新对象
Z
zhuangqian 已提交
654
	 * 
Z
zhuangqian 已提交
655 656 657 658 659 660
	 * @param <T>
	 * @param className 类名,完整类路径
	 * @param methodName 方法名
	 * @param args 参数,必须严格对应指定方法的参数类型和数量
	 * @return 返回结果
	 */
Z
zhuangqian 已提交
661
	public static <T> T invoke(String className, String methodName, Object[] args) {
Z
zhuangqian 已提交
662 663
		return invoke(className, methodName, false, args);
	}
Z
zhuangqian 已提交
664

Z
zhuangqian 已提交
665 666 667 668
	/**
	 * 执行方法<br>
	 * 可执行Private方法,也可执行static方法<br>
	 * 执行非static方法时,必须满足对象有默认构造方法<br>
Z
zhuangqian 已提交
669
	 * 
Z
zhuangqian 已提交
670 671 672 673 674 675 676
	 * @param <T>
	 * @param className 类名,完整类路径
	 * @param methodName 方法名
	 * @param isSingleton 是否为单例对象,如果此参数为false,每次执行方法时创建一个新对象
	 * @param args 参数,必须严格对应指定方法的参数类型和数量
	 * @return 返回结果
	 */
Z
zhuangqian 已提交
677
	public static <T> T invoke(String className, String methodName, boolean isSingleton, Object[] args) {
Z
zhuangqian 已提交
678 679
		Class<Object> clazz = loadClass(className);
		try {
Z
zhuangqian 已提交
680
			return invoke(isSingleton ? Singleton.create(clazz) : clazz.newInstance(), methodName, args);
Z
zhuangqian 已提交
681 682 683 684
		} catch (Exception e) {
			throw new ToolBoxException(e);
		}
	}
Z
zhuangqian 已提交
685 686 687 688

	/**
	 * 执行方法<br>
	 * 可执行Private方法,也可执行static方法<br>
Z
zhuangqian 已提交
689
	 * 
Z
zhuangqian 已提交
690 691 692 693 694 695
	 * @param <T>
	 * @param obj 对象
	 * @param methodName 方法名
	 * @param args 参数,必须严格对应指定方法的参数类型和数量
	 * @return 返回结果
	 */
Z
zhuangqian 已提交
696
	public static <T> T invoke(Object obj, String methodName, Object[] args) {
Z
zhuangqian 已提交
697 698 699 700 701 702 703
		try {
			final Method method = getDeclaredMethod(obj, methodName, args);
			return invoke(obj, method, args);
		} catch (Exception e) {
			throw new ToolBoxException(e);
		}
	}
Z
zhuangqian 已提交
704

Z
zhuangqian 已提交
705 706
	/**
	 * 执行方法
Z
zhuangqian 已提交
707
	 * 
Z
zhuangqian 已提交
708 709 710 711
	 * @param obj 对象
	 * @param method 方法(对象方法或static方法都可)
	 * @param args 参数对象
	 * @return 结果
Z
zhuangqian 已提交
712
	 * @throws ToolBoxException IllegalAccessException and IllegalArgumentException
Z
zhuangqian 已提交
713 714 715
	 * @throws InvocationTargetException
	 */
	@SuppressWarnings("unchecked")
Z
zhuangqian 已提交
716
	public static <T> T invoke(Object obj, Method method, Object[] args) throws InvocationTargetException {
Z
zhuangqian 已提交
717 718 719
		if (false == method.isAccessible()) {
			method.setAccessible(true);
		}
Z
zhuangqian 已提交
720 721 722 723
		try {
			return (T) method.invoke(isStatic(method) ? null : obj, args);
		} catch (IllegalAccessException | IllegalArgumentException e) {
			throw new ToolBoxException(e);
Z
zhuangqian 已提交
724 725
		}
	}
Z
zhuangqian 已提交
726 727
	// ---------------------------------------------------------------------------------------------------- Invoke end

Z
zhuangqian 已提交
728 729 730
	/**
	 * 新建代理对象<br>
	 * 动态代理类对象用于动态创建一个代理对象,可以在调用接口方法的时候动态执行相应逻辑
Z
zhuangqian 已提交
731
	 * 
Z
zhuangqian 已提交
732 733 734 735 736
	 * @param interfaceClass 被代理接口
	 * @param invocationHandler 代理执行类,此类用于实现具体的接口方法
	 * @return 被代理接口
	 */
	@SuppressWarnings("unchecked")
Z
zhuangqian 已提交
737 738
	public static <T> T newProxyInstance(Class<T> interfaceClass, InvocationHandler invocationHandler) {
		return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class<?>[] { interfaceClass }, invocationHandler);
Z
zhuangqian 已提交
739
	}
Z
zhuangqian 已提交
740

Z
zhuangqian 已提交
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
	/**
	 * 新建代理对象(cglib)<br>
	 * 动态代理类对象用于动态创建一个代理对象,可以在调用接口方法的时候动态执行相应逻辑
	 * @param clazz 被代理类
	 * @param methodInterceptor 代理执行类,此类用于实现具体的接口方法
	 * @return 被代理类
	 */
	@SuppressWarnings("unchecked")
	public static <T> T newProxyCglibFactory(Class<T> clazz, MethodInterceptor methodInterceptor){
		try {
			Class<?> superClass = Class.forName(clazz.getName());
			Enhancer hancer = new Enhancer();
			hancer.setSuperclass(superClass);
			hancer.setCallback(methodInterceptor);
			return (T) hancer.create();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			return null;
		}
	}
	
Z
zhuangqian 已提交
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
	/**
	 * 是否为包装类型
	 * 
	 * @param clazz 类
	 * @return 是否为包装类型
	 */
	public static boolean isPrimitiveWrapper(Class<?> clazz) {
		if (null == clazz) {
			return false;
		}
		return BasicType.wrapperPrimitiveMap.containsKey(clazz);
	}

	/**
	 * 是否为基本类型(包括包装类和原始类)
	 * 
	 * @param clazz 类
	 * @return 是否为基本类型
	 */
	public static boolean isBasicType(Class<?> clazz) {
		if (null == clazz) {
			return false;
		}
		return (clazz.isPrimitive() || isPrimitiveWrapper(clazz));
	}

	/**
	 * 是否简单值类型或简单值类型的数组<br>
	 * 包括:原始类型,、String、other CharSequence, a Number, a Date, a URI, a URL, a Locale or a Class及其数组
	 * 
	 * @param clazz 属性类
	 * @return 是否简单值类型或简单值类型的数组
	 */
	public static boolean isSimpleTypeOrArray(Class<?> clazz) {
		if (null == clazz) {
			return false;
		}
		return isSimpleValueType(clazz) || (clazz.isArray() && isSimpleValueType(clazz.getComponentType()));
	}

	/**
	 * 是否为简单值类型<br>
	 * 包括:原始类型,、String、other CharSequence, a Number, a Date, a URI, a URL, a Locale or a Class.
	 * 
	 * @param clazz 类
	 * @return 是否为简单值类型
	 */
	public static boolean isSimpleValueType(Class<?> clazz) {
		return isBasicType(clazz) || clazz.isEnum() || CharSequence.class.isAssignableFrom(clazz) || Number.class.isAssignableFrom(clazz) || Date.class.isAssignableFrom(clazz) || clazz
				.equals(URI.class) || clazz.equals(URL.class) || clazz.equals(Locale.class) || clazz.equals(Class.class);
	}

	/**
	 * 检查目标类是否可以从原类转化<br>
	 * 转化包括:<br>
	 * 1、原类是对象,目标类型是原类型实现的接口<br>
	 * 2、目标类型是原类型的父类<br>
	 * 3、两者是原始类型或者包装类型(相互转换)
	 * 
	 * @param targetType 目标类型
	 * @param sourceType 原类型
	 * @return 是否可转化
	 */
	public static boolean isAssignable(Class<?> targetType, Class<?> sourceType) {
		if (null == targetType || null == sourceType) {
			return false;
		}
Z
zhuangqian 已提交
829

Z
zhuangqian 已提交
830 831 832 833
		// 对象类型
		if (targetType.isAssignableFrom(sourceType)) {
			return true;
		}
Z
zhuangqian 已提交
834

Z
zhuangqian 已提交
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889
		// 基本类型
		if (targetType.isPrimitive()) {
			// 原始类型
			Class<?> resolvedPrimitive = BasicType.wrapperPrimitiveMap.get(sourceType);
			if (resolvedPrimitive != null && targetType.equals(resolvedPrimitive)) {
				return true;
			}
		} else {
			// 包装类型
			Class<?> resolvedWrapper = BasicType.primitiveWrapperMap.get(sourceType);
			if (resolvedWrapper != null && targetType.isAssignableFrom(resolvedWrapper)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 指定类是否为Public
	 * 
	 * @param clazz 类
	 * @return 是否为public
	 */
	public static boolean isPublic(Class<?> clazz) {
		if (null == clazz) {
			throw new NullPointerException("Class to provided is null.");
		}
		return Modifier.isPublic(clazz.getModifiers());
	}

	/**
	 * 指定方法是否为Public
	 * 
	 * @param method 方法
	 * @return 是否为public
	 */
	public static boolean isPublic(Method method) {
		if (null == method) {
			throw new NullPointerException("Method to provided is null.");
		}
		return isPublic(method.getDeclaringClass());
	}

	/**
	 * 指定类是否为非public
	 * 
	 * @param clazz 类
	 * @return 是否为非public
	 */
	public static boolean isNotPublic(Class<?> clazz) {
		return false == isPublic(clazz);
	}

	/**
	 * 指定方法是否为非public
Z
zhuangqian 已提交
890
	 * 
Z
zhuangqian 已提交
891 892 893 894 895 896
	 * @param method 方法
	 * @return 是否为非public
	 */
	public static boolean isNotPublic(Method method) {
		return false == isPublic(method);
	}
Z
zhuangqian 已提交
897

Z
zhuangqian 已提交
898 899
	/**
	 * 是否为静态方法
Z
zhuangqian 已提交
900
	 * 
Z
zhuangqian 已提交
901 902 903
	 * @param method 方法
	 * @return 是否为静态方法
	 */
Z
zhuangqian 已提交
904
	public static boolean isStatic(Method method) {
Z
zhuangqian 已提交
905 906 907 908 909 910 911 912 913 914
		return Modifier.isStatic(method.getModifiers());
	}

	/**
	 * 设置方法为可访问
	 * 
	 * @param method 方法
	 * @return 方法
	 */
	public static Method setAccessible(Method method) {
Z
zhuangqian 已提交
915
		if (null != method && ClassKit.isNotPublic(method)) {
Z
zhuangqian 已提交
916 917 918 919
			method.setAccessible(true);
		}
		return method;
	}
Z
zhuangqian 已提交
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945

	/**
	 * 是否为抽象类
	 * 
	 * @param clazz 类
	 * @return 是否为抽象类
	 */
	public static boolean isAbstract(Class<?> clazz) {
		return Modifier.isAbstract(clazz.getModifiers());
	}

	/**
	 * 是否为标准的类<br>
	 * 这个类必须:<br>
	 * 1、非接口 2、非抽象类 3、非Enum枚举 4、非数组 5、非注解 6、非原始类型(int, long等)
	 * 
	 * @param clazz 类
	 * @return 是否为标准类
	 */
	public static boolean isNormalClass(Class<?> clazz) {
		return null != clazz && false == clazz.isInterface() && false == isAbstract(clazz) && false == clazz.isEnum() && false == clazz.isArray() && false == clazz.isAnnotation() && false == clazz
				.isSynthetic() && false == clazz.isPrimitive();
	}

	// --------------------------------------------------------------------------------------------------- Private method start
	/**
Z
zhuangqian 已提交
946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976
	 * 文件过滤器,过滤掉不需要的文件<br>
	 * 只保留Class文件、目录和Jar
	 */
	private static FileFilter fileFilter = new FileFilter(){
		@Override
		public boolean accept(File pathname) {
			return isClass(pathname.getName()) || pathname.isDirectory() || isJarFile(pathname);
		}
	};

	/**
	 * 改变 com -> com. 避免在比较的时候把比如 completeTestSuite.class类扫描进去,如果没有"."</br>
	 * 那class里面com开头的class类也会被扫描进去,其实名称后面或前面需要一个 ".",来添加包的特征
	 * 
	 * @param packageName
	 * @return 格式化后的包名
	 */
	private static String getWellFormedPackageName(String packageName) {
		return packageName.lastIndexOf(StrKit.DOT) != packageName.length() - 1 ? packageName + StrKit.DOT : packageName;
	}

	/**
	 * 填充满足条件的class 填充到 classes<br>
	 * 同时会判断给定的路径是否为Jar包内的路径,如果是,则扫描此Jar包
	 * 
	 * @param path Class文件路径或者所在目录Jar包路径
	 * @param packageName 需要扫面的包名
	 * @param classFilter class过滤器
	 * @param classes List 集合
	 */
	private static void fillClasses(String path, String packageName, ClassFilter classFilter, Set<Class<?>> classes) {
Z
zhuangqian 已提交
977
		// 判定给定的路径是否为Jar
Z
zhuangqian 已提交
978
		int index = path.lastIndexOf(FileKit.JAR_PATH_EXT);
Z
zhuangqian 已提交
979 980 981 982
		if (index != -1) {
			// Jar文件
			path = path.substring(0, index + FileKit.JAR_FILE_EXT.length()); // 截取jar路径
			path = StrKit.removePrefix(path, FileKit.PATH_FILE_PRE); // 去掉文件前缀
Z
zhuangqian 已提交
983
			processJarFile(new File(path), packageName, classFilter, classes);
Z
zhuangqian 已提交
984
		} else {
Z
zhuangqian 已提交
985 986 987
			fillClasses(path, new File(path), packageName, classFilter, classes);
		}
	}
Z
zhuangqian 已提交
988

Z
zhuangqian 已提交
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
	/**
	 * 填充满足条件的class 填充到 classes
	 * 
	 * @param classPath 类文件所在目录,当包名为空时使用此参数,用于截掉类名前面的文件路径
	 * @param file Class文件或者所在目录Jar包文件
	 * @param packageName 需要扫面的包名
	 * @param classFilter class过滤器
	 * @param classes List 集合
	 */
	private static void fillClasses(String classPath, File file, String packageName, ClassFilter classFilter, Set<Class<?>> classes) {
		if (file.isDirectory()) {
			processDirectory(classPath, file, packageName, classFilter, classes);
		} else if (isClassFile(file)) {
			processClassFile(classPath, file, packageName, classFilter, classes);
		} else if (isJarFile(file)) {
			processJarFile(file, packageName, classFilter, classes);
		}
	}

	/**
	 * 处理如果为目录的情况,需要递归调用 fillClasses方法
	 * 
	 * @param directory 目录
	 * @param packageName 包名
	 * @param classFilter 类过滤器
	 * @param classes 类集合
	 */
	private static void processDirectory(String classPath, File directory, String packageName, ClassFilter classFilter, Set<Class<?>> classes) {
		for (File file : directory.listFiles(fileFilter)) {
			fillClasses(classPath, file, packageName, classFilter, classes);
		}
	}

	/**
	 * 处理为class文件的情况,填充满足条件的class 到 classes
	 * 
	 * @param classPath 类文件所在目录,当包名为空时使用此参数,用于截掉类名前面的文件路径
	 * @param file class文件
	 * @param packageName 包名
	 * @param classFilter 类过滤器
	 * @param classes 类集合
	 */
	private static void processClassFile(String classPath, File file, String packageName, ClassFilter classFilter, Set<Class<?>> classes) {
Z
zhuangqian 已提交
1032
		if (false == classPath.endsWith(File.separator)) {
Z
zhuangqian 已提交
1033 1034 1035
			classPath += File.separator;
		}
		String path = file.getAbsolutePath();
Z
zhuangqian 已提交
1036
		if (StrKit.isEmpty(packageName)) {
Z
zhuangqian 已提交
1037 1038 1039
			path = StrKit.removePrefix(path, classPath);
		}
		final String filePathWithDot = path.replace(File.separator, StrKit.DOT);
Z
zhuangqian 已提交
1040

Z
zhuangqian 已提交
1041 1042 1043
		int subIndex = -1;
		if ((subIndex = filePathWithDot.indexOf(packageName)) != -1) {
			final int endIndex = filePathWithDot.lastIndexOf(FileKit.CLASS_EXT);
Z
zhuangqian 已提交
1044

Z
zhuangqian 已提交
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
			final String className = filePathWithDot.substring(subIndex, endIndex);
			fillClass(className, packageName, classes, classFilter);
		}
	}

	/**
	 * 处理为jar文件的情况,填充满足条件的class 到 classes
	 * 
	 * @param file jar文件
	 * @param packageName 包名
	 * @param classFilter 类过滤器
	 * @param classes 类集合
	 */
	private static void processJarFile(File file, String packageName, ClassFilter classFilter, Set<Class<?>> classes) {
		try {
			for (JarEntry entry : Collections.list(new JarFile(file).entries())) {
				if (isClass(entry.getName())) {
					final String className = entry.getName().replace(StrKit.SLASH, StrKit.DOT).replace(FileKit.CLASS_EXT, StrKit.EMPTY);
					fillClass(className, packageName, classes, classFilter);
				}
			}
		} catch (Throwable ex) {
			log.error(ex.getMessage(), ex);
		}
	}

	/**
	 * 填充class 到 classes
	 * 
	 * @param className 类名
	 * @param packageName 包名
	 * @param classes 类集合
	 * @param classFilter 类过滤器
	 */
	private static void fillClass(String className, String packageName, Set<Class<?>> classes, ClassFilter classFilter) {
		if (className.startsWith(packageName)) {
			try {
				final Class<?> clazz = Class.forName(className, false, getClassLoader());
				if (classFilter == null || classFilter.accept(clazz)) {
					classes.add(clazz);
				}
			} catch (Throwable ex) {
Z
zhuangqian 已提交
1087 1088
				// Log.error(log, ex, "Load class [{}] error!", className);
				// Pass Load Error.
Z
zhuangqian 已提交
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
			}
		}
	}

	/**
	 * @param file 文件
	 * @return 是否为类文件
	 */
	private static boolean isClassFile(File file) {
		return isClass(file.getName());
	}
Z
zhuangqian 已提交
1100

Z
zhuangqian 已提交
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
	/**
	 * @param fileName 文件名
	 * @return 是否为类文件
	 */
	private static boolean isClass(String fileName) {
		return fileName.endsWith(FileKit.CLASS_EXT);
	}

	/**
	 * @param file 文件
	 * @return是否为Jar文件
	 */
	private static boolean isJarFile(File file) {
		return file.getName().endsWith(FileKit.JAR_FILE_EXT);
	}
Z
zhuangqian 已提交
1116 1117
	// --------------------------------------------------------------------------------------------------- Private method end

Z
zhuangqian 已提交
1118 1119 1120 1121 1122 1123
	/**
	 * 类过滤器,用于过滤不需要加载的类<br>
	 */
	public interface ClassFilter {
		boolean accept(Class<?> clazz);
	}
Z
zhuangqian 已提交
1124 1125 1126 1127 1128 1129 1130
}  interface Filter<T> {
	/**
	 * 修改过滤后的结果
	 * @param t 被过滤的对象
	 * @return 修改后的对象,如果被过滤返回<code>null</code>
	 */
	public T modify(T t);
Z
zhuangqian 已提交
1131
}