java - 你把这个称作什么?

标签 java

是否有此技术的名称(方法调用返回对象,在同一行上对其进行另一个方法调用)?

String pAID = commonAssets.getApplicationServerSettings().getSetting("plivoAuthID");

代替

ApplicationServerSettings applicationServerSettings = commonAssets.getApplicationServerSettings();
String pAID = applicationServerSettings.getSetting("plivoAuthID");

此外,当我执行第一个时,Eclipse 不会提示我导入类 ApplicationServerSettings,但如果我使用第二个代码样式,它会提示。

另外,这两种风格仅仅是偏好吗?

最佳答案

该技术称为 method chaining .

String pAID = commonAssets.getApplicationServerSettings().getSetting("plivoAuthID");

来自维基的定义:

Method chaining, also known as named parameter idiom, is a common syntax for invoking multiple method calls in object-oriented programming languages. Each method returns an object, allowing the calls to be chained together in a single statement without requiring variables to store the intermediate results.[1] Local variable declarations are syntactic sugar because of the difficulty humans have with deeply nested method calls.[2][3] A method chain is also known as a train wreck due to the increase in the number of methods that come one after another in the same line that occurs as more methods are chained together[4] even though line breaks are often added between methods.

你的第二个问题:

此外,当我执行第一个时,Eclipse 不会提示我导入类 ApplicationServerSettings,但如果我使用第二个代码样式,它会提示。

  • 再次从定义“每个方法返回一个对象,允许调用在一个语句中链接在一起,而不需要变量来存储中间结果。”这就是它不提示你的原因导入类 ApplicationServerSettings

另一个看起来更简单的例子(除了你介绍的want):

看看维基示例:

class Person {
    private String name;
    private int age;

    // In addition to having the side-effect of setting the attributes in question,
    // the setters return "this" (the current Person object) to allow for further chained method calls.

    public Person setName(String name) {
        this.name = name;
        return this;
    }

    public Person setAge(int age) {
        this.age = age;
        return this;
    }

    public void introduce() {
        System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
    }

    // Usage:
    public static void main(String[] args) {
        Person person = new Person();
        // Output: Hello, my name is Peter and I am 21 years old.
        person.setName("Peter").setAge(21).introduce();
    }
}

关于java - 你把这个称作什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32405359/

相关文章:

java - 在Java中让图像绕圈飞行

java - 如何从跨度分隔的标签中获取动态文本

java - 如何解释原子 Action ?

java - isSticky按钮当前状态Android

java - 在 Java Swing 中循环遍历容器内的嵌套容器

java - 当方法 toString 不起作用时,如何在 java 中打印字符串数组?

java - 如何在 Android 中使用 For 循环创建对象数组

java - 无法通过appium在android模拟器中启动计算器

java - Swing JTextArea 插入符事件

java - 使用 MBROVERLAP 在 Java 中进行 mysql 查询