Java 15-getter具有不同返回类型的记录

问题描述

是否可以在Java 15中实现类似的东西?

record Something(
        SomeId id,MyProp myProp,MaybeProp maybeProp
){
    public Something(SomeId id,MyProp myProp){
        this(id,myProp,null);
    }

    public Optional<MaybeProp> maybeProp(){ //problematic line
        return Optional.ofNullable(maybeProp);
    }
}

在这里我得到了例外

(return type of accessor method maybeProp() must match the type of record component maybeProp)

所以-我了解问题出在哪里;但是还有其他解决方案吗?如何在记录中包含可选成员,而我不需要使用Optional.of()进行初始化?

解决方法

您不能隐藏或更改记录字段的自动生成的读取访问器的返回类型。

一种实现所需内容的方法是让记录实现一个接口,然后使用该接口代替记录类型:

interface PossibleSomething {
    Optional<Something> maybeSomething();
}

record SomethingRecord(Something something) implements PossibleSomething {
    public Optional<Something> maybeSomething() {
        return Optional.ofNullable(something);
    }
}

// user code:
PossibleSomething mySomething = new SomethingRecord(something);
mySomething.maybeSomething().ifPresent(...)

通过在调用代码中使用PossibleSomething,您明确声明您不需要直接访问该字段,而仅通过接口的访问器对其进行访问。

根据设计理念,记录明确旨在(根据JEP)支持将数据建模为数据。换句话说,它们的用例是当您拥有要存储的直接不变数据并为用户提供直接访问权限时。这就是为什么他们不支持更改访问者的原因:这不是记录的目的。我在上面显示的模式(即,一个记录实现了一个接口以隐藏访问权限)是一种将记录的使用隐藏为实现细节并控制对字段的访问的方法。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...