468,315 Members | 1,457 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,315 developers. It's quick & easy.

constructor loading it's object from a file

i'd like to have a constructor that loads an object from disk and returns
it... kinda like:

class MyClass
{
MyClass(File f)
{
ObjectInputStream s = new ObjectInputStream(new
FileInputStream(f));
this = (MyClass)s.readObject();
}
}

now i know you cannot do this because this in the constructor is a final
variable...

is there trick that i don't know of that can do this?

p.s., before i get the typical responses... i already am using a static
factory method to accomplish the same thing... i'm just looking to make it
even easier to use my classes.

thanks for any help,

murat
--
Murat Tasan
mx**@po.cwru.edu
ta***@eecs.cwru.edu
mu*********@cwru.edu
http://genomics.cwru.edu

Jul 17 '05 #1
2 1721
Murat Tasan wrote:
i'd like to have a constructor that loads an object from disk and returns
it... kinda like:

class MyClass
{
MyClass(File f)
{
ObjectInputStream s = new ObjectInputStream(new
FileInputStream(f));
this = (MyClass)s.readObject();
}
}

now i know you cannot do this because this in the constructor is a final
variable...

is there trick that i don't know of that can do this?

p.s., before i get the typical responses... i already am using a static
factory method to accomplish the same thing... i'm just looking to make it
even easier to use my classes.


What makes a constructor "easier" than a static method?

If you really wanted to do this you could read in the object from the
file and then copy all of its instance variables. Sounds like too much
work and too error prone for my taste however.

Ray

P.S. Can't tell if you edited it for posting, but don't forget to close
your streams in a finally clause.

Jul 17 '05 #2
> class MyClass
{
MyClass(File f)
{
ObjectInputStream s = new ObjectInputStream(new
FileInputStream(f));
this = (MyClass)s.readObject();
}
}


how about instead of reading your object into this , read it in some
temporary local object variable & then perform member by member copy
into this
something of this sort

class MyClass
{
int x;
MyClass(File f)
{
MyClass temp;
ObjectInputStream s = new ObjectInputStream(new
FileInputStream(f));
temp= (MyClass)s.readObject();
this.x=temp.x; //member by member
copy for all members
}
}

hope this should help
regards
amey
Jul 17 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

8 posts views Thread by RonHiler | last post: by
10 posts views Thread by linkspeed | last post: by
4 posts views Thread by Gustaf Liljegren | last post: by
1 post views Thread by GRiN | last post: by
74 posts views Thread by Zytan | last post: by
reply views Thread by NPC403 | last post: by
reply views Thread by Teichintx | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.