在dubbo中发现一个获取类加载器的好代码

    1. /**
    2. * get class loader
    3. *
    4. * @param clazz
    5. * @return class loader
    6. */
    7. public static ClassLoader getClassLoader(Class<?> clazz) {
    8. ClassLoader cl = null;
    9. try {
    10. cl = Thread.currentThread().getContextClassLoader();
    11. } catch (Throwable ex) {
    12. // Cannot access thread context ClassLoader - falling back to system class loader...
    13. }
    14. if (cl == null) {
    15. // No thread context class loader -> use class loader of this class.
    16. cl = clazz.getClassLoader();
    17. if (cl == null) {
    18. // getClassLoader() returning null indicates the bootstrap ClassLoader
    19. try {
    20. cl = ClassLoader.getSystemClassLoader();
    21. } catch (Throwable ex) {
    22. // Cannot access system ClassLoader - oh well, maybe the caller can live with null...
    23. }
    24. }
    25. }
    26. return cl;
    27. }