use*_*245 1 java methods chaining bukkit
我遇到了以下代码行:
getLogger().info("Text Goes Here"); // This command outputs the text to console
Run Code Online (Sandbox Code Playgroud)
我理解对象如何工作和被调用的基础知识,但在我在youtube上观看的视频中,vivz(作者),从未解释过在方法中调用方法(至少我认为在上面的代码中发生了这种情况).
他解释说
ClassName.variable
xVariable.method()
Run Code Online (Sandbox Code Playgroud)
但没有任何关系
someMethod().anotherMethod();
Run Code Online (Sandbox Code Playgroud)
在初学者的术语中,任何人都可以解释这个概念或对这里发生的事情的一些解释吗?
基本上,我想知道,如果info()是一个方法里面getLogger(),或者是什么getLogger(),并info()在这种情况下?
这称为方法链接.
方法链接是
invoking multiple method calls面向对象编程语言的常用语法.每个方法都返回一个对象,允许在单个语句中将调用链接在一起,而不需要变量来存储中间结果.
它不是方法里面的方法,这是两个方法调用.首先getLogger()调用,然后调用返回值(object)info(String).您在一个语句中链接两个方法调用.
我将举例说明一下String.concat():
public static void main(String[] args) {
String first = "First";
// Storing the resulting instance and then call again.
String s1 = first.concat(" Second");
s1 = s1.concat(" Third.");
System.out.println(s1);
// This is method chaining using String class with concat() method.
String s2 = first.concat(" Second").concat(" Third.");
System.out.println(s2);
}
Run Code Online (Sandbox Code Playgroud)
这里String.concat()返回String连接后的实例.现在,您可以选择将实例存储在变量中,然后再次调用concat()on或直接使用相同的实例.