Difference between Loading a class using ClassLoader and Class.forName

后端 未结 9 1068
梦如初夏
梦如初夏 2020-11-29 20:38

Below are 2 code snippets

The first one uses ClassLoader class to load a specified class

ClassLoader cls = ClassLoader.getSystemClassL

9条回答
  •  没有蜡笔的小新
    2020-11-29 21:14

    The 2nd approach loads a class using a ClassLoader

     public static Class forName(String className) 
                    throws ClassNotFoundException {
            return forName0(className, true, ClassLoader.getCallerClassLoader());
    

    This is what the JavaDoc says:

    forName(String name, boolean initialize, ClassLoader loader)
    

    The specified class loader is used to load the class or interface. If the parameter loader is null, the class is loaded through the bootstrap class loader.

    So, the 2nd option uses the System ClassLoader (which is, in essence, what it does in the first option).

提交回复
热议问题