如果没有加载过才加载的写法

1. 加载完就不加载的写法

1.1是不是可以参考双亲委派机制

1.2那就分析一下ClassLoader源码吧

protected Class loadClass(String name, boolean resolve)
        throws ClassNotFoundException
    {
            // First, check if the class has already been loaded
            Class c = findLoadedClass(name);
            if (c == null) {
                try {
                    if (parent != null) {
                            // 注释1 parent 为父加载器,可以自定义一个classLoader 依次打印出所有父类
                        c = parent.loadClass(name, false);
                    } else {
                        c = findBootstrapClassOrNull(name);
                    }
                } catch (ClassNotFoundException e) {
                    // ClassNotFoundException thrown if class not found
                    // from the non-null parent class loader
                }

                if (c == null) {
                    // If still not found, then invoke findClass in order
                    // to find the class.
                    c = findClass(name);
                }
            }
            return c;
    }

注释1 :默认构造函数的classLoader为 PathClassLoader
parent 为父加载器,可以自定义一个classLoader 依次打印出所有parent

 private static ClassLoader createSystemClassLoader() {
        String classPath = System.getProperty("java.class.path", ".");
        String librarySearchPath = System.getProperty("java.library.path", "");

        // String[] paths = classPath.split(":");
        // URL[] urls = new URL[paths.length];
        // for (int i = 0; i < paths.length; i++) {
        // try {
        // urls[i] = new URL("file://" + paths[i]);
        // }
        // catch (Exception ex) {
        // ex.printStackTrace();
        // }
        // }
        //
        // return new java.net.URLClassLoader(urls, null);

        // TODO Make this a java.net.URLClassLoader once we have those?
        return new PathClassLoader(classPath, librarySearchPath, BootClassLoader.getInstance());
    }
2.1做法比较简单但是有几个要注意的地方
  1. 尽量不要在方法中直接return
  2. 注意函数单一性原则

总结

东西很简单,就是修改bug的时候突然想到的,大家遇到不知道怎么实现比较合理的时候其实可以参考源码,既可以了解源码是怎么实现的(说不定面试的时候用的上呢),也可以用到实践中。虽然简单但是也有意义!

你可能感兴趣的:(如果没有加载过才加载的写法)