位置:org.springframework.util
�实现接口:无
继承类:无
作用:提供构建类缓存数据与初始化内容的相关方法
一、效果
二、API
// 主要列举几个典型API
/*
获取类加载器
获取顺序:
当前线程上下文类加载器—>当前类类加载器—>系统启动类加载器
*/
public static ClassLoader getDefaultClassLoader() {
ClassLoader cl = null;
try {
//获取当前线程的context class loader
cl = Thread.currentThread().getContextClassLoader();
}catch (Throwable ex) {
}
if (cl == null) {
// 如果没有context loader,使用当前类的类加载器;
cl = ClassUtils.class.getClassLoader();
if (cl == null) {
// 如果当前类加载器无法获取,获得bootstrap ClassLoader
try {
cl = ClassLoader.getSystemClassLoader();
} catch (Throwable ex) {
}
}
}
return cl;
}
/*
得到类上指定的public方法,一个标准的反射使用
为了处理重载的异常,程序通过clazz.getMethods()先得到所有方法,然后再去对比方法名的方式来获取没有
参数列表的方法,而不是使用clazz.getMethod(methodName)来直接获取没有参数列表的方法
*/
public static Method getMethod(Class<?> clazz, String methodName, Class<?>... paramTypes) {
Assert.notNull(clazz, "Class must not be null");
Assert.notNull(methodName, "Method name must not be null");
if (paramTypes != null) {
try {
//如果指定了参数类型,直接使用getMethod方法;
return clazz.getMethod(methodName, paramTypes);
}catch (NoSuchMethodException ex) {
throw new IllegalStateException("Expected method not found: " + ex);
}
}else {
Set<Method> candidates = new HashSet<Method>(1);
Method[] methods = clazz.getMethods();
for (Method method : methods) {
if (methodName.equals(method.getName())) {
candidates.add(method);
}
}
if (candidates.size() == 1) {
return candidates.iterator().next();
}else if (candidates.isEmpty()) {
throw new IllegalStateException("Expected method not found: " + clazz + "." + methodName);
}else {
throw new IllegalStateException("No unique method found: " + clazz + "." + methodName);
}
}
}
三、总结
ClassUtils中包含了大量的方法,虽然很多方法在平时的开发中使用不到,但是其中涉及到多种类加载器,代理等内容。
四、补充
无