Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / November 2005

Tip: Looking for answers? Try searching our database.

Ways to instantiate a Class

Thread view: 
Lian Liming - 01 Nov 2005 07:27 GMT
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!
Benji - 01 Nov 2005 07:46 GMT
> <snip>

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

you can use reflection.

Signature

Of making better designs there is no end,
 and much refactoring wearies the body.

Lian Liming - 01 Nov 2005 08:01 GMT
> > <snip>
>
> 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.

> you can use reflection.
>
> --
> Of making better designs there is no end,
>   and much refactoring wearies the body.
Bjorn Abelli - 01 Nov 2005 11:40 GMT
"Lian Liming" wrote...
>> > <snip>
>>
[quoted text clipped - 4 lines]
> 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
Roedy Green - 01 Nov 2005 08:22 GMT
>   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"?

there is reflection  newInstance.

See http://mindprod.com/jgloss/classforname.html

A Factory inside usually just does a new.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Eric Sosman - 01 Nov 2005 18:08 GMT
Roedy Green wrote On 11/01/05 02:22,:

>>  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"?
>
>  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().

Signature

Eric.Sosman@sun.com

Eike Preuss - 02 Nov 2005 13:23 GMT
> Roedy Green wrote On 11/01/05 02:22,:
>>
[quoted text clipped - 8 lines]
> 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?
Bjorn Abelli - 02 Nov 2005 14:19 GMT
"Eike Preuss" wrote...

>>>> Recently I learned to use "factory method" to instantiate
>>>> a class. But I am still wondering if there are other ways
[quoted text clipped - 4 lines]
>>
>>     ... which is just an obscure way to run a constructor.

But it is still another "way" to instantiate, than to use "new".

>> The constructor-less instantiation methods I can think of
>> are clone() and readObject().
[quoted text clipped - 7 lines]
> 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
Roedy Green - 02 Nov 2005 14:33 GMT
On Wed, 02 Nov 2005 13:23:59 +0100, Eike Preuss
<usenet@eikepreuss.REMOVE.de> wrote, quoted or indirectly quoted
someone who said :

>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
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Eike Preuss - 02 Nov 2005 15:24 GMT
> Object.clone creates a new object and copies all fields of this object
> into it in a bit by bit fashion.
[quoted text clipped - 15 lines]
>    ...
>    } // end Rabbit
Should have read the javadoc... thanks for the reminder!
Roedy Green - 02 Nov 2005 14:37 GMT
On Wed, 02 Nov 2005 13:23:59 +0100, Eike Preuss
<usenet@eikepreuss.REMOVE.de> wrote, quoted or indirectly quoted
someone who said :

>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.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Tor Iver Wilhelmsen - 02 Nov 2005 16:28 GMT
> 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;
}
Roedy Green - 03 Nov 2005 08:16 GMT
On 02 Nov 2005 16:51:33 +0100, Tor Iver Wilhelmsen
<jadedgamer@hotmail.com> wrote, quoted or indirectly quoted someone
who said :

>By having the constructor not assign any values to fields*, and add an
>init() method that does the initialization.
[quoted text clipped - 10 lines]
>  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.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Chris Uppal - 02 Nov 2005 15:09 GMT
> 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


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.