Re: constructor loading it's object from a file

From: Raymond DeCampo (rdecampo_at_hold-the-spam.twcny.rr.com)
Date: 12/05/03


Date: Fri, 05 Dec 2003 02:32:30 GMT

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.



Relevant Pages

  • Re: My LogGenerator.java wont compile - too many errors - help
    ... I meant static factory method, it's what you implemented to replace the ... constructor that you made private. ... Consider the singleton pattern. ...
    (comp.lang.java.help)
  • Re: Could an object refuse to be created!?
    ... that you might instead use a factory method. ... also capable of returning null rather than throwing an exception. ... > Hi Kevin, ... throw an Exception in the object's constructor. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Observer Design Pattern
    ... require 'singleton' ... singletons would have a static factory method ") to make themselves useful. ... how does the factory method decide which constructor to invoke? ... Will the include statement make the constructors become private if they were declared public? ...
    (comp.object)
  • Re: My LogGenerator.java wont compile - too many errors - help
    ... A static factory method is a normal method, getName) that is used to create instances of a class. ... Normally instances are created by a constructor. ... Consider the singleton pattern. ...
    (comp.lang.java.help)
  • Re: Creating funny objects
    ... > I have always been taught to creat object in the form ... Basically, it's more flexible than a constructor, because a constructor ... code, SAXParser is an abstract class, so it's not possible to instantiate ... The factory method will use "new" in some way, ...
    (comp.lang.java.programmer)