Discussions

General J2EE: Class.forName() vs getContextClassLoader().loadClass()

  1. Class.forName() vs getContextClassLoader().loadClass() (4 messages)

    Hi all, I've stumbled by these two methods recently: Class.forName(className); Thread.currentThread().getContextClassLoader().loadClass(className); I want to know the reason why most programmer is cheering for the latter method? Have been reading a lot about classloading articles but have not got a conclusion yet?
  2. because of ...[ Go to top ]

    They are not the equivalent. :-) they use different class loaders. Class.forName(String) == Class.forName(className, true, currentLoader) where currentLoader denotes the defining class loader of the current class. Thread.currentThread().getContextClassLoader().loadClass(className); will load class using context class loader.
  3. thanks![ Go to top ]

    thanks a lot!I have found some explains online and i have got them already!thanks anyway!
  4. the biggest difference ive seen is the later can load from outside of the same jar. so if the class your using to load is in a different jar to the class you want, then it would otherwise fail with class.forname. i suggest using the context version as default since you never know where your code will end up. this is particually important when working with application containers

  5. the biggest difference ive seen is the later can load from outside of the same jar. so if the class your using to load is in a different jar to the class you want, then it would otherwise fail with class.forname. i suggest using the context version as default since you never know where your code will end up. this is particually important when working with application containers

     

    I don't think so.

    Class.forName() can load any class from any jar that exist in the class path,