简体   繁体   English

有没有办法让构造函数在 Java 中返回 == null 的 object?

[英]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?我必须在 Foo 中做什么才能使这成为现实?

No, there is no way to have a new object be null . 不,没有办法让新对象为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"); 你可以轻松编写自己的异常,或者只使用throw new Exception("foo failed to initialize"); and capture that. 抓住那个。

Writing your own Exception: http://www.javaplex.com/blog/java-creating-custom-exceptions/ 编写自己的例外: 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. 不,构造函数没有返回值,但无论何时使用“new”,您都可以创建对象的引用。 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. 在处理构造函数中的错误方面,Java专家时事通讯不久前就讨论了这个主题。 Might be worth a read: http://www.javaspecialists.eu/archive/Issue120.html 可能值得一读: http//www.javaspecialists.eu/archive/Issue120.html

No, it's not possible for a constructor to return null. 不,构造函数不可能返回null。 If there's a problem creating the object, then the constructor should throw an exception. 如果创建对象时出现问题,那么构造函数应抛出异常。

Take the FileInputStream class for example. FileInputStream类为例。 This class is used to read data from a file. 该类用于从文件中读取数据。 If a non-existent file is passed into the constructor, it throws a FileNotFoundException : 如果将不存在的文件传递给构造函数,则会抛出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. 11 年后,我们仍然有这个问题。 To summarize the valid responses and add an idea as well:总结有效回复并添加一个想法:

Idea 1: Create a wrapper class to work like a factory.想法 1:创建一个包装器 class 以像工厂一样工作。 This wrapper class will create new instances of the inner class if the data is valid.如果数据有效,这个包装器 class 将创建内部 class 的新实例。 (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. (来自 user975484)//如果你是单独工作,想法 1 很好,但如果你正在为学校或公司项目创建 object,那么你可能不允许使用工厂。

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. (来自 CamelSlack)//如果用户捕获并处理错误,想法 2 也很棒。 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.思路三:object中函数校验数据后返回null或默认数据。 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. //对于被迫遵循一套过于严格的要求的学生和员工来说,想法 3 可能是唯一的选择。 Really isn't useful unless idea 1 and 2 cannot be used.除非不能使用想法 1 和 2,否则真的没有用。

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? 如果这真的是你需要的,为什么不使用一个可以返回Foo的新实例或null的函数?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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