在 Java 中调用静态函数时构造函数的运行方式



我希望一个类检查输入是否有效,并且所有有效的输入都记录在文本文件中。

因此,在构造中,它会读取文本文件并将所有有效输入放入 HashSet 中。然后我static函数来接收输入并检查输入是否在 HashSet 中。

代码结构如下所示:

public class Validator {
    HashSet validInputs;
    public Validator() {
        //read in
    }
    public static boolean validate(String in) {
        //check and return
    }
}

然后在其他类中,我需要使用该类来验证字符串Validator。代码是这样的:

...
String a = XXX;
boolean valid = Validator.validate(a);
...

我还没有测试过代码,但我有两个问题:

  1. 行得通吗?是否读入了有效的输入文本文件?
  2. 类何时读取文本文件?
  3. 每次调用函数validate()时,Validator都会读取文本文件吗?

行得通吗?是否读入了有效的输入文本文件?

,那行不通。

您的方法应该是实例方法,以便它可以访问其他实例成员。

public boolean validate(String in) {
    //check and return
}

类何时读取文本文件?

您必须先构造该类,然后才能使用它。在构造函数中读取文本文件。


每次调用函数 validate() 时,验证器都会读取文本文件吗?

不。调用 new Validator() 时调用构造函数。

您可以使用单例和非静态validate -方法:

public class Validator {
    private static Validator instance = null;
    /**
     * Do not use new Validator; use Validator.getInstance() instead.
     */
    private Validator() {
        // read in
    }
    public static Validator getInstance() {
        if(instance == null) {
            instance = new Validatorr();
        }
        return instance;
    }
    public boolean validate(String str) {
        // check and return
    }
}

在您需要validate某些东西的任何地方,请使用:

Validator.getInstance().validate()

注意:以这种方式实现的单例模式的副作用是,如果不使用验证程序,则不会创建验证程序,也不会读取in。 这可能是您想要的,也可能不是您想要的。

不会。 validInputs将绑定到Validator实例,并且无法从静态方法中引用它。你需要的是一个静态块:

public final class Validator {
    private static HashSet validInputs;
    private Validator() {}
    static {
        //read in
    }
    public static boolean validate(String in) {

     //check and return
    }
}

如果这样做:

When will the class read in the text file? -  When the class is loaded by the Class loader.
Will Validator read the text file every time I call the function validate()? -  No, only when the class is loaded.

不,在创建Validator实例之前,您将无法访问validInputs new Validator()

  1. 不会,您的文件在使用时不会被读入。
  2. 当您创建 Validator 的新实例时,将读取该文件。
  3. 不。只有当您有new Validator()时,才会读入它。

如果您希望能够以静态方式访问此方法,请考虑使用 Singleton

最新更新