简体   繁体   中英

Is there a way to have a constructor return an object that == null in Java?

I have a feeling the answer is "no" but thought I'd ask just in case...

pseudo code:

Foo foo = new Foo();

if(foo != null){
    foo.useMe();
}else{
   System.out.println("foo failed to initialize");
}

What would I have to do in Foo to make this a reality?

No, there is no way to have a new object be null . This, of course, assumes that there was not an error in the constructor, but if there is, then you will not be able to use the variable anyway.

For more information on the Class Instance Creation Expression, I recommend the language specification .

Typically you would just have it throw an exception for this situation. You can easily write your own exception or just use something like throw new Exception("foo failed to initialize"); and capture that.

Writing your own Exception: http://www.javaplex.com/blog/java-creating-custom-exceptions/

No, constructors have no return value, but whenever you use "new" you get a create a reference to an object. I think what you want is this:

class Factory
{
    static MyClass getMyClass()
    {
    if(true or false expression)
        return new MyClass();
    else if(true or false expression)
        return null;
    }

}

and then you can create your class like this

MyClass bla = Factory.getMyClass();

if(null)
    do something

I knew this is impossible; but just out of curiosity, I tried out a piece of code.

public class Test {

  public Test () {
    this = null;
  }

}

And of course it failed to compile since "this" is final.

No, this is not possible. By convention, if an object fails to initialize, an exception is thrown.

No, this isn't possible - you can however throw a checked exception in the constructor which would need to be caught at the other end if you really want this type of behaviour.

In terms of dealing with errors in constructors a Java specialist newsletter looked at this topic a while back. Might be worth a read: http://www.javaspecialists.eu/archive/Issue120.html

No, it's not possible for a constructor to return null. If there's a problem creating the object, then the constructor should throw an exception.

Take the FileInputStream class for example. This class is used to read data from a file. If a non-existent file is passed into the constructor, it throws a FileNotFoundException :

try{
  FileInputStream in = new FileInputStream("file.txt");
} catch (FileNotFoundException e){
  System.out.println("File 'file.txt' doesn't exist.");
}

11 years later and we still have the issue. To summarize the valid responses and add an idea as well:

Idea 1: Create a wrapper class to work like a factory. This wrapper class will create new instances of the inner class if the data is valid. (by user975484) //Idea 1 is great if you are working solo, but if you are creating an object for a school or company project then you may not be allowed to use a factory.

Idea 2: Throw an exception if data is invalid in the constructor. (by CamelSlack) //Idea 2 is great as well if the user catches and handles the error. However, you may not be allowed to use this method for school or company rules. I believe that this may be the best solution if you can use it.

Idea 3: return null or default data from functions in the object after verifying data. In essence, run your data verification before running functions. //Idea 3 might be the only option for students and employees who are forced to follow an overly strict set of requirements. Really isn't useful unless idea 1 and 2 cannot be used.

Does it have to be a constructor? If this is truly what you need, why not use a function that can return a new instance of Foo or null?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM