java 类处理工具

时间:2024-01-12 08:45:38
public class ClassUtils {

    private static final Logger LOGGER  = LoggerFactory.getLogger(ClassUtils.class);

    /**
* 返回某个父类底下所有的实现类
*/public static List<Class> getSubClassesByParentClass(Class parentClass) { List<Class> returnClassList = new ArrayList<Class>(); String packageName = parentClass.getPackage().getName();
try {
List<Class> allClass = getClassesByPackageName(packageName);
for (int i = 0; i < allClass.size(); i++) {
if (parentClass.isAssignableFrom(allClass.get(i))) {
if (!parentClass.equals(allClass.get(i))) {
returnClassList.add(allClass.get(i));
}
}
}
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
return returnClassList;
} /**
* 从一个包中查找出所有类,在jar包中不能查找
*
* @param packageName
* @return
* @throws IOException
* @throws ClassNotFoundException
*/
public static List<Class> getClassesByPackageName(String packageName)
throws IOException, ClassNotFoundException {
ClassLoader classLoader = Thread.currentThread()
.getContextClassLoader();
String path = packageName.replace('.', '/');
Enumeration<URL> resources = classLoader.getResources(path);
List<File> dirs = new ArrayList<File>();
while (resources.hasMoreElements()) {
URL resource = resources.nextElement();
dirs.add(new File(resource.getFile()));
}
ArrayList<Class> classes = new ArrayList<Class>();
for (File directory : dirs) {
classes.addAll(findClasses(directory, packageName));
}
return classes;
} /**
*
* @param directory
* @param packageName
* @return
* @throws ClassNotFoundException
*/
public static List<Class> findClasses(File directory, String packageName)
throws ClassNotFoundException {
List<Class> classes = new ArrayList<Class>();
if (!directory.exists()) {
return classes;
}
File[] files = directory.listFiles();
for (File file : files) {
if (file.isDirectory()) {
assert !file.getName().contains(".");
classes.addAll(findClasses(file, packageName + '.'
+ file.getName()));
} else if (file.getName().endsWith(".class")) {
classes.add(Class.forName(packageName
+ "."
+ file.getName().substring(0,
file.getName().length() - 6)));
}
}
return classes;
} /**
* 对Map类型数据按Key排序
*
* @param map
*/public static List sort(Map map) {
List list = new ArrayList(map.keySet());
Collections.sort(list, new Comparator() {
public int compare(Object a, Object b) {
return a.toString().toLowerCase().compareTo(
b.toString().toLowerCase());
}
});
return list;
}
}