• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

What's the difference between ClassLoader.xx and Class.forName(String className)

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If we want to initialize a class by its name, we can write as below:
1. Class.forName(className);
2. getClass().getClassLoader().loadClass(className).newInstance();
I just want to know, what is the difference between these 2 ways.
Thanks!
Regard's
Leslie W
 
author
Posts: 154
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
1. Returns a Class object.
2. Returns an instance of the class.
To make the two equivalent, you would need to change (1) to Class.forName(className).newInstance();
If you do that, then basically there's no difference in the result because both of them use the default class loader. But note you can't use (2) within a static method because getClass() itself is not static.
Hope this helps,
David Peterson
 
Leslie Wu
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you very much
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic