简体   繁体   English

如何理解用Java连接在一起的创建类或方法的概念

[英]How to understand the concept of create classes or methods joined together in Java

I want to know the concept of inner methods called one time example in Java. 我想知道Java中称为一次示例的内部方法的概念。

Object ob = new Object().toString().charAt(0);

My question: 我的问题:

Are toString() and charAt(0); toString()charAt(0); are classes or methods joined together using dot? 类或方法使用点连接在一起吗?

I confused how to ask these question if you understand my bad grammar please help me. 我很困惑如何问这些问题,如果您理解我的语法不好,请帮助我。

Each method of those returns a object, you are just chaining the call in the next object. 这些方法的每个方法都会返回一个对象,您只需将调用链接到下一个对象中即可。

The equivalent of 相当于

char c = new Object().toString().charAt(0);

is the following code: 是以下代码:

Object obj = new Object();
String objectStr = obj.toString();
char c = objectStr.charAt(0);

It is called "fluent interfaces" or method chaining. 这称为“流利接口”或方法链接。 We can achive this with returning of object itself. 我们可以通过返回对象本身来达到这一目的。 Fluent apis used everywhere basic example of it is Builder classes. 到处都使用流利的api的基本示例是Builder类。

In Java, Optional class or stream api is an example of fluent apis. 在Java中,可选类或流api是流利的api的示例。

Here is an example builder class with fluend methods: 这是带有fluend方法的示例构建器类:

class ObjectBuilder {
    private SomeObject someObject = new SomeObject();

    public ObjectBuilder withPropertyX(int x) {
        someObject.setPropertyX(x);
        return this;
    }

    public ObjectBuilder withPropertyY(String y) {
        someObject.setPropertyY(y);
        return this;
    }

    public SomeObject build() {
        return someObject;
    }

}

ObjectBuilder builder = new ObjectBuilder();

SomeObject someObject = builder.withPropertyX(5).withPropertyY("test").build();

Another example with stream api: 流API的另一个示例:

List<String> students = new ArrayList();

    students.add("alice");
    students.add("jack");
    students.add("john");

    students.stream()
            .map(String::toUpperCase)
            .forEach(System.out::println);

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

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