Ways to instantiate a Class

L

Lian Liming

Hi all,

Recently I learned to use "factory method" to instantiate a class.
But I am still wondering if there are other ways to instantiate a class
besides the stand using way of using "new" and way of using "factory
method"?

Thanks in advance!
 
L

Lian Liming

Benji said:
Well, the factory pattern uses "new"...so I'm not sure what you mean...

Ok, my fault. I am still a java newbie. I mean, the stand way
instantiating a Clas s is like "ClassA a = new ClassA()", and the
factory way is like "ClassA a = factory.getClassA()". Hope it is clear
this time.
 
B

Bjorn Abelli

Ok, my fault. I am still a java newbie. I mean, the stand way
instantiating a Clas s is like "ClassA a = new ClassA()", and the
factory way is like "ClassA a = factory.getClassA()". Hope it is clear
this time.

It's still as Benji said, the factory method itself uses new, or reflection,
so it's no "magic" behind the scenes.

The method "getClass()" probably looks something like this:

....
public ClassA getClassA() {
ClassA newA = new ClassA();
// then it does something with the instance...
return newA;
}
....

....or it uses reflection...

When you're executing...

ClassA a = factory.getClassA();

....it's not the sentence itself that instantiates the object, it's
instantiated (with new or with reflection) somewhere inside the factory
method.


// Bjorn A
 
E

Eric Sosman

Roedy Green wrote On 11/01/05 02:22,:
there is reflection newInstance.

... which is just an obscure way to run a constructor.
The constructor-less instantiation methods I can think of
are clone() and readObject().
 
E

Eike Preuss

Roedy Green wrote On 11/01/05 02:22,:

... which is just an obscure way to run a constructor.
The constructor-less instantiation methods I can think of
are clone() and readObject().

clone() is a user implemented create and copy operation, Object#clone()
does absolutely nothing. So a call of clone() is just an obscure way to
call some other method that performs the real instance creation.
And with each object this could be a different one, 'new', reflection,
whatever. Am I mislead somewhere?

How does readObject() work? Does it simply dump the binary data to some
memory and return a reference to this memory space?
 
B

Bjorn Abelli

...
But it is still another "way" to instantiate, than to use "new".
clone() is a user implemented create and copy operation, Object#clone()
does absolutely nothing. So a call of clone() is just an obscure way to
call some other method that performs the real instance creation.
And with each object this could be a different one, 'new', reflection,
whatever. Am I mislead somewhere?

How does readObject() work? Does it simply dump the binary data
to some memory and return a reference to this memory space?

I became so curious about this, so I tried to read up on the subject. Not
that I succeeded to find a definitive answer, but I think I got fairly
close.

"readObject" relies heavily on its JNI-implementation. It's not quite to
"dump it into memory", but close enough to call it different from reflection
in Java only. It also resolves references to other serialized objects, etc.

To make it short, I would say that deserialization could be considered a
third way of "instantiating" objects, though it semantically isn't to
instantiate a "new" object, just to restore an "old" one... ;-)

We're now up to three ways to "instantiate":

- using the "new" keyword
- through reflection
- through deserialization

Anyone up for a fourth... ;-)

// Bjorn A
 
R

Roedy Green

clone() is a user implemented create and copy operation, Object#clone()
does absolutely nothing. So a call of clone() is just an obscure way to
call some other method that performs the real instance creation.

Object.clone creates a new object and copies all fields of this object
into it in a bit by bit fashion.

class Rabbit implements Cloneable
{
...
public Object clone()
{
try
{
return super.clone();
}
catch ( CloneNotSupportedException e )
{
return null;
}
}
...
} // end Rabbit
 
R

Roedy Green

How does readObject() work?

It does not actually execute the constructor. At the JVM level it does
a new without calling the constructor. They might have pulled that
off by composing or patching a class file manually. I don't know how
you could get that effect in Java itself.
 
C

Chris Uppal

Eike said:
clone() is a user implemented create and copy operation, Object#clone()
does absolutely nothing.

Take a second look at the JavaDoc for Object.clone(), you'll find it does a lot
more than you think.

-- chris
 
E

Eike Preuss

Object.clone creates a new object and copies all fields of this object
into it in a bit by bit fashion.

class Rabbit implements Cloneable
{
...
public Object clone()
{
try
{
return super.clone();
}
catch ( CloneNotSupportedException e )
{
return null;
}
}
...
} // end Rabbit
Should have read the javadoc... thanks for the reminder!
 
T

Tor Iver Wilhelmsen

Roedy Green said:
It does not actually execute the constructor. At the JVM level it does
a new without calling the constructor. They might have pulled that
off by composing or patching a class file manually. I don't know how
you could get that effect in Java itself.

By having the constructor not assign any values to fields*, and add an
init() method that does the initialization.

* This of course includes assignments in declarations:

int foo = 5;

is the same as

int foo;

public void <init>() {
foo = 5;
}
 
R

Roedy Green

By having the constructor not assign any values to fields*, and add an
init() method that does the initialization.

* This of course includes assignments in declarations:

int foo = 5;

is the same as

int foo;

public void <init>() {
foo = 5;
}

readObject has to work with arbitrary objects. It can't go composing
constructors or methods for them. It can't even count on a no-arg
constructor existing.

I spent a while looking at the code in java.util.ObjectInputStream. It
is pretty hairy.

readOrdinaryObject(boolean unshared)

uses desc.newInstance() to create an empty shell of an object later
filled in with the read.

That puzzled me on two counts:

1. what if there is no no-arg constructor?

2. I distinctly read somewhere that readObject does NOT invoke the
constructor.

The explanation is in the javaDoc for ObjectStreamClass.newInstance:

Creates a new instance of the represented class. If the class is
externalizable, invokes its public no-arg constructor; otherwise, if
the class is serializable, invokes the no-arg constructor of the first
non-serializable superclass. Throws UnsupportedOperationException if
his class descriptor is not associated with a class, if the associated
class is non-serializable or if the appropriate no-arg constructor is
inaccessible/unavailable.

On read, the code in the outer layer constructors of the serialized
objects does not get called, just the inner non-serializable layers,
e.g. Object.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top