public static void main(String[] args) {
//判断当前应用是否加载了某个类
String str = "main.CollectionsUtilsTest";
try {
//方法一
Class<?> forName = Class.forName(str);
System.out.println(forName);
//方法二
Class<?> aClass = ClassUtilsTest.class.getClassLoader().loadClass(str);
System.out.println(aClass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//方法三:Spring自带工具ClassUtils
boolean present = ClassUtils.isPresent(str, null);
System.out.println(present);
}
主要说一下第三个方法
本质上还是通过Class.forName();
public static boolean isPresent(String className,@Nullable ClassLoader classLoader) {
try {
forName(className, classLoader);
return true;
}
catch (Throwable ex) {
// Class or one of its dependencies is not present...
return false;
}
}
网友评论