The Artima Developer Community
Sponsored Link

Java Answers Forum
How to cancel the creation of an instance

1 reply on 1 page. Most recent reply: May 3, 2004 4:29 AM by Matthias Neumair

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 1 reply on 1 page
guest

Posts: 9
Nickname: guest
Registered: Dec, 2003

How to cancel the creation of an instance Posted: May 3, 2004 3:17 AM
Reply to this message Reply
Advertisement
How can I cancel the creation of an instance of a class from its constructor?

MyClass c = new MyClass();
System.out.println (c==null);

I'd like this in some cases to print true (e.g. if the constructor fails due to some error).
NB. I do not want the constructor to throw an exception that I'd have to catch.

An example on an existing class would be:

new ArrayList (null);

this should return a null ArrayList reference. How can I implement it?
Thanks.


Matthias Neumair

Posts: 660
Nickname: neumi
Registered: Sep, 2003

Re: How to cancel the creation of an instance Posted: May 3, 2004 4:29 AM
Reply to this message Reply
A Constructor should (can?) never return null.

If you really need to do it using a constructor, throw an exception, if the argument is null.

Class MyClass {
private MyClass (Object myParameter) throws ArgumentIsNullException {
if (myParameter == null)
throw new ArgumentIsNullException(...);
}
class ArgumentIsNullException extends Exception {
...
}
}





Otherwise I would recommend this way to do it:

Class MyClass {
/** No Instance can be created directly
*/
private MyClass (Object myParameter) {
}

/** This method does the trick. It returns null if a null value was passed as argument.
*/
public static MyClass createInstanceOfMyClass (Object myParameter) {
return myParameter == null? null : new MyClass(myParameter);
}
}

Flat View: This topic has 1 reply on 1 page
Topic: GUI application Previous Topic   Next Topic Topic: I need help with this java application

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use