Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Difference between creating objects

 
Manish Jaju
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is difference between making the object by new operator and .newInstance, just like

if I have a class OBJ so I can create object like

OBJ A = new OBJ();

and

Class obj= Class.forName(OBJ);
OBJ B = obj.newInstance();

So please clarify the difference between making the object by these two ways.

Thanking you.
Manish
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the normal case there's not much difference. One correction - you want a String name in class.forName("classname");

I use a lot of class.forName(name).newInstance() where the classname comes from configuration. We can add new classes at run time without changing any code, compiling or deploying jars. You can't do that trick with new.

newInstance has optional parameters for custom or non-default class loaders. For example, we found a place in J2EE where the default classloader doesn't know about classpaths that were added in server configuration after the JVM started up. So we have go get the classloader that loaded the current class and use that to load another class. If that made no sense, just file away a note that someday when you get a "class not found" error on a perfectly good class, you may have to research classloaders.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first one is simpler and less error prone.

The second one works when you don't know the class name at compile time.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic