简体   繁体   English

了解Java中将方法保存到对象中

[英]Understanding the saving of Methods into Objects in Java

In the javadoc there is an example of code in the class Pattern, which I do not understand regarding to the concept.在 javadoc 中有一个 class 模式中的代码示例,我不了解这个概念。

Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("aaaaab");
boolean b = m.matches();
  • The compile method is static and gets saved into an object of the class Pattern.编译方法是 static 并保存到 class 模式的 object 中。 How does that work?这是如何运作的?
  • The method matcher gets called from the object of the instance p and gets stored into a variable of the type Matcher.方法 matcher 从实例 p 的 object 调用,并存储到 Matcher 类型的变量中。 How does that work?这是如何运作的?

It's possible to look at the Java source code in your IDE / online .可以在您的 IDE / online中查看 Java 源代码。 Thus, lets go through what's really happening here:因此,让 go 通过这里真正发生的事情:

public static Pattern compile(String regex) {
    return new Pattern(regex, 0);
}

The static compile method doesn't actually compile or "save anything to the class", it just creates a new Pattern instance for you and returns it. static compile方法实际上并不编译或“将任何内容保存到类中”,它只是为您创建一个新的Pattern实例并返回它。


private Pattern(String p, int f) {
    //...
}

The Pattern class's constructor is private , meaning that you're not able to instantiate it yourself directly; Pattern类的构造函数是private的,这意味着你不能自己直接实例化它; meaning that you have to use Pattern.compile and friends.这意味着您必须使用Pattern.compile和朋友。


Q: Why did they design it this way??问:他们为什么要这样设计?

The main idea is that the constructor they've got going on is a bit weird --- it takes in that flags int, and constructors in other classes in the standard library are worse, to the point where you might need quite in-depth knowledge of the class's inner workings in order to use them.主要思想是他们正在进行的构造函数有点奇怪——它接受了 int 标志,而标准库中其他类中的构造函数更糟糕,以至于你可能需要相当深入了解类的内部工作,以便使用它们。 So, it can make sense to move those to being private implementation details, and then make a few methods which create your class correctly for all the use cases people need, and to be reasonably consistent with how you do it.因此,将这些转移到私有实现细节是有意义的,然后制定一些方法来为人们需要的所有用例正确创建 class,并与您的操作方式保持合理一致。

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

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