功能列表
- 獲取指定 classloader 中已加載的類;
- 獲取指定 classloader 中已加載且?guī)в兄付ㄗ⒔獾念悾?/li>
源代碼
package com.dotions.classloader;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.List;
import java.util.Vector;
import java.util.stream.Collectors;
/**
* <p>
* Class 相關(guān)工具類
* </p>
*
* Created by wyf0931 on 2018-03-27.
*/
public class ClassUtil {
/**
* 獲取指定 classloader 中已加載的類
*
* @param cl
*/
@SuppressWarnings("unchecked")
public static Vector<Class<?>> getLoadedClasses(ClassLoader cl) {
if (cl == null) {
return null;
}
try {
Field classes = ClassLoader.class.getDeclaredField("classes");
classes.setAccessible(true);
return (Vector<Class<?>>) classes.get(cl);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
/**
* 獲取指定 classloader 中已加載且?guī)в兄付ㄗ⒔獾念? *
* @param cl
* @param annotationClass
*/
public static List<Class<?>> getLoadedClassesByAnnotation(ClassLoader cl,
Class<? extends Annotation> annotationClass) {
Vector<Class<?>> classes = getLoadedClasses(cl);
if (classes == null || classes.isEmpty()) {
return Collections.emptyList();
}
return classes.stream().filter(c -> c.isAnnotationPresent(annotationClass)).collect(Collectors.toList());
}
}