Java 对象解构

问题描述 投票:0回答:3

在 javascript 中,存在对象解构,因此我们可以分解对象,如果多次重复使用中间对象,则只需使用结束键即可。例如)

const person = {
  firstName: "Bob",
  lastName: "Marley",
  city: "Space"
}

因此,我们可以像这样解构它,而不是调用

person.<>
来获取每个值

console.log(person.firstName) 
console.log(person.lastName) 
console.log(person.city) 

解构:

const { firstName, lastName, city } = person;

然后这样打电话:

console.log(firstName)
console.log(lastName)
console.log(city)

Java中有类似的东西吗?我有一个 Java 对象,我需要从中获取值,并且必须调用长中间对象名称,如下所示:

myOuterObject.getIntermediateObject().getThisSuperImportantGetter()
myOuterObject.getIntermediateObject().getThisSecondImportantGetter()
...

我希望以某种方式解构它,只需调用最后一个方法

getThisSuperImportantGetter()
getThisSecondImportantGetter()
以获得更清晰的代码。

java object destructuring
3个回答
28
投票

Java 语言架构师 Brian Goetz 最近谈到了在即将推出的 Java 版本中添加解构。在他的论文中查找侧边栏:模式匹配章节:

迈向更好的序列化

我非常不喜欢当前的语法提案,但根据 Brian 的说法,您的用例将如下所示(请注意,此时这只是一个提案,不适用于任何当前版本的 Java):

public class Person {
    private final String firstName, lastName, city;

    // Constructor
    public Person(String firstName, String lastName, String city) { 
        this.firstName = firstName;
        this.lastName = lastName;
        this.city = city;
    }

    // Deconstruction pattern
    public pattern Person(String firstName, String lastName, String city) { 
        firstName = this.firstName;
        lastName = this.lastName;
        city = this.city;
    }
}

您应该能够在实例检查中使用该解构模式,如下所示:

if (o instanceof Person(var firstName, lastName, city)) {
   System.out.println(firstName);
   System.out.println(lastName);
   System.out.println(city);
}

抱歉,Brian 在他的示例中没有提到任何直接解构赋值,我不确定是否以及如何支持这些赋值。

旁注:我确实看到了与构造函数的预期相似性,但我个人不太喜欢当前的提案,因为“解构函数”的参数感觉就像是外参数(Brian 在他的纸)。对我来说,在每个人都在谈论不变性并让你的方法参数

final
的世界里,这是相当违反直觉的。

我宁愿看到 Java 跳过栅栏并支持多值返回类型。大致如下:

    public (String firstName, String lastName, String city) deconstruct() { 
        return (this.firstName, this.lastName, this.city);
    }

23
投票

据我所知,java不支持这个。

其他名为 Kotlin 的 JVM 语言也支持此功能

科特林 |解构声明


0
投票

如上所述,Java 不支持像 Javascript 那样的解构赋值。但是,Groovy,一种 jvm 语言,也支持它,如下所示:

def (a,b,c) = [10, 20, 'foo']

或者像这样的数据类型:

def (int i, String j) = [10, 'foo']
© www.soinside.com 2019 - 2024. All rights reserved.