位置:org.springframework.util
�实现接口:无
继承类:无
作用:提供构建类缓存数据与初始化内容的相关方法

一、效果

主要spring内部构建使用,无具体演示效果

二、API

  1. // 主要列举几个典型API
  2. /*
  3. 获取类加载器
  4. 获取顺序:
  5. 当前线程上下文类加载器—>当前类类加载器—>系统启动类加载器
  6. */
  7. public static ClassLoader getDefaultClassLoader() {
  8. ClassLoader cl = null;
  9. try {
  10. //获取当前线程的context class loader
  11. cl = Thread.currentThread().getContextClassLoader();
  12. }catch (Throwable ex) {
  13. }
  14. if (cl == null) {
  15. // 如果没有context loader,使用当前类的类加载器;
  16. cl = ClassUtils.class.getClassLoader();
  17. if (cl == null) {
  18. // 如果当前类加载器无法获取,获得bootstrap ClassLoader
  19. try {
  20. cl = ClassLoader.getSystemClassLoader();
  21. } catch (Throwable ex) {
  22. }
  23. }
  24. }
  25. return cl;
  26. }
  27. /*
  28. 得到类上指定的public方法,一个标准的反射使用
  29. 为了处理重载的异常,程序通过clazz.getMethods()先得到所有方法,然后再去对比方法名的方式来获取没有
  30. 参数列表的方法,而不是使用clazz.getMethod(methodName)来直接获取没有参数列表的方法
  31. */
  32. public static Method getMethod(Class<?> clazz, String methodName, Class<?>... paramTypes) {
  33. Assert.notNull(clazz, "Class must not be null");
  34. Assert.notNull(methodName, "Method name must not be null");
  35. if (paramTypes != null) {
  36. try {
  37. //如果指定了参数类型,直接使用getMethod方法;
  38. return clazz.getMethod(methodName, paramTypes);
  39. }catch (NoSuchMethodException ex) {
  40. throw new IllegalStateException("Expected method not found: " + ex);
  41. }
  42. }else {
  43. Set<Method> candidates = new HashSet<Method>(1);
  44. Method[] methods = clazz.getMethods();
  45. for (Method method : methods) {
  46. if (methodName.equals(method.getName())) {
  47. candidates.add(method);
  48. }
  49. }
  50. if (candidates.size() == 1) {
  51. return candidates.iterator().next();
  52. }else if (candidates.isEmpty()) {
  53. throw new IllegalStateException("Expected method not found: " + clazz + "." + methodName);
  54. }else {
  55. throw new IllegalStateException("No unique method found: " + clazz + "." + methodName);
  56. }
  57. }
  58. }

三、总结

ClassUtils中包含了大量的方法,虽然很多方法在平时的开发中使用不到,但是其中涉及到多种类加载器,代理等内容。

四、补充


参考资料: Spring中的各种Utils(四):ClassUtils详解