Java: Difference between Class.forName and ClassLoader.loadClass

前端 未结 5 1779
故里飘歌
故里飘歌 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:35

    Shaun's answer is more or less correct except few omissions/small errors:

    • Class.forName associates the class w/ the ClassLoader (regardless if any other parent loads it for real), hence ClassLoader.findLoadedClass is successful next time. That's a very, very important point, most ClassLoader would try Class c = findLoadedClass(name); if (c!=null) return c; as first statements bypassing the whole find/look up part. Calling ClassLoader.load directly will not add the class to the loaded ones.

    The case has implications when loaded via graph alike structure of ClassLoader, i.e. not using parent only to lookup first.

    • Initialization of the class is performed in loadClass of the ClassLoader w/ code like that: if (resolve) resolveClass(c); and the ClassLoader can actually skip resolve it it feels like, unrecommended but possible.

    What are the do's and dont's to using these two methods?

    Unless you have very strong idea why you want ClassLoader.loadClass(String), do not use it directly. In all other case, always rely on Class.forName(name, true, classLoader).

    Overall Class loading is next to an art and it cannot be covered in a simple answer (not joking about art part)

提交回复
热议问题