Two Laptop Bag*
The moose likes Beginning Java and the fly likes Difference between creating objects Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Difference between creating objects" Watch "Difference between creating objects" New topic
Author

Difference between creating objects

Manish Jaju
Greenhorn

Joined: Jul 21, 2004
Posts: 24
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

Joined: Jan 29, 2003
Posts: 8791
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.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
The first one is simpler and less error prone.

The second one works when you don't know the class name at compile time.


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Difference between creating objects
 
Similar Threads
PriorityQueue ,add and compare object
object creation
Java ---== operato
confusion in if condition
Two Questions: Why = null, and why actual variable not method?...