ClassUtil

功能列表

  • 获取指定 classloader 中已加载的类;
  • 获取指定 classloader 中已加载且带有指定注解的类;

源代码

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;

/**
 * 

* Class 相关工具类 *

* * Created by wyf0931 on 2018-03-27. */ public class ClassUtil { /** * 获取指定 classloader 中已加载的类 * * @param cl */ @SuppressWarnings("unchecked") public static Vector> getLoadedClasses(ClassLoader cl) { if (cl == null) { return null; } try { Field classes = ClassLoader.class.getDeclaredField("classes"); classes.setAccessible(true); return (Vector>) 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 中已加载且带有指定注解的类 * * @param cl * @param annotationClass */ public static List> getLoadedClassesByAnnotation(ClassLoader cl, Class annotationClass) { Vector> classes = getLoadedClasses(cl); if (classes == null || classes.isEmpty()) { return Collections.emptyList(); } return classes.stream().filter(c -> c.isAnnotationPresent(annotationClass)).collect(Collectors.toList()); } }

你可能感兴趣的:(ClassUtil)