By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,778 Members | 1,074 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,778 IT Pros & Developers. It's quick & easy.

constructor loading it's object from a file

P: n/a
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
Share this Question
Share on Google+
2 Replies


P: n/a
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

P: n/a
> 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.