Java: Difference between Class.forName and ClassLoader.loadClass

前端 未结 5 1799
故里飘歌
故里飘歌 2020-12-22 23:51

What is the difference between Class.forName and ClassLoader.loadClass in the following codes:

Class theClass = Class.forName("         


        
5条回答
  •  余生分开走
    2020-12-23 00:32

    This line won't compile:

    Class theClass = ClassLoader.loadClass("SomeImpl");
    

    because loadClass is not a static method of ClassLoader.

    To fix this problem, create a ClassLoader object as follows in one of 3 possible ways:

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    ClassLoader classLoader = Main.class.getClassLoader();      // Assuming in class Main
    ClassLoader classLoader = getClass().getClassLoader();      // works in any class
    

    then call:

    Class theClass = classLoader.loadClass("SomeImpl");
    

    -dbednar

提交回复
热议问题