在 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 语言架构师 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;
}
}
您应该能够像这样在 instanceof 检查中使用该解构模式:
if (o instanceof Person(var firstName, lastName, city)) {
System.out.println(firstName);
System.out.println(lastName);
System.out.println(city);
}
抱歉,Brian 在他的例子中没有提到任何直接的解构赋值,我不确定这些是否以及如何得到支持。
旁注:我确实看到了与构造函数的预期相似性,但我个人不太喜欢当前的提案,因为“解构函数”的参数感觉像是输出参数(布赖恩在他的论文中说了很多)。对我来说,在每个人都在谈论不变性并使您的方法参数 final
的世界中,这是相当违反直觉的。
我宁愿看到 Java 越过围栏转而支持多值返回类型。类似的东西:
public (String firstName, String lastName, String city) deconstruct() {
return (this.firstName, this.lastName, this.city);
}
关于Java对象解构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56586093/