用作 JSF 值的 Java 记录

cos*_*scu 1 jsf el java-record

我正在使用 Java 15 和 JSF 2.3 以及 PrimeFaces 8 开发一个简单的 JSF Web 应用程序(主要用于学习),并且我正在使用一个简单的 Java 记录来对实体进行建模。该应用程序不使用任何数据库。

我的问题是是否可以将 java 记录用作 xhtml 页面中的值,如下所示

    <p:column headerText="Id">
        <h:outputText value="#{car.randomId}" />
    </p:column>

Run Code Online (Sandbox Code Playgroud)

因为我收到以下错误 javax.el.PropertyNotFoundException: The class 'com.company.Car' does not have the property 'id'.。我试过放置car.year(),但没有用。记录的定义是这个

public record Car (String randomId, String randomBrand, int randomYear, String randomColor, int randomPrice, boolean randomSoldState) {
}
Run Code Online (Sandbox Code Playgroud)

在 pom.xml 中,我使用以下 api

        <dependency>
            <groupId>jakarta.platform</groupId>
            <artifactId>jakarta.jakartaee-api</artifactId>
            <version>8.0.0</version>
            <scope>provided</scope>
        </dependency>
Run Code Online (Sandbox Code Playgroud)

感谢您的帮助!

Bal*_*usC 8

从技术上讲,问题不在于 JSF,而在于 EL。异常的包名已经暗示这一点:javax.el.PropertyNotFoundException。正在使用的 EL 版本尚不能识别 Java 记录。Jakarta EE 8 与 Java 8 相关联,但 Java Records 功能是在 Java 14 中引入的。理论上,它最早只会在与 Java 14 相关的 Jakarta EE 版本相关的 EL 版本中得到本机支持。但即使这样也不太可能因为 Java Records 仅可用作“预览功能”(因此默认情况下根本不启用)。

回到你的具体问题,使用方法表达式语法#{car.randomId()}在 WildFly 21 上确实对我有用。无论如何,EL 解析总是可以使用自定义ELResolver. 这是一个启动示例,它根据作为属性检查记录Class#isRecord()并收集可用字段Class#getRecordComponents()

public class RecordELResolver extends ELResolver {

    private static final Map<Class<?>, Map<String, PropertyDescriptor>> RECORD_PROPERTY_DESCRIPTOR_CACHE = new ConcurrentHashMap<>();

    private static boolean isRecord(Object base) {
        return base != null && base.getClass().isRecord();
    }
    
    private static Map<String, PropertyDescriptor> getRecordPropertyDescriptors(Object base) {
        return RECORD_PROPERTY_DESCRIPTOR_CACHE
            .computeIfAbsent(base.getClass(), clazz -> Arrays
                .stream(clazz.getRecordComponents())
                .collect(Collectors
                    .toMap(RecordComponent::getName, recordComponent -> {
                        try {
                            return new PropertyDescriptor(recordComponent.getName(), recordComponent.getAccessor(), null);
                        }
                        catch (IntrospectionException e) {
                            throw new IllegalStateException(e);
                        }
                    })));
    }
    
    private static PropertyDescriptor getRecordPropertyDescriptor(Object base, Object property) {
        PropertyDescriptor descriptor = getRecordPropertyDescriptors(base).get(property);
        
        if (descriptor == null) {
            throw new PropertyNotFoundException("The record '" + base.getClass().getName() + "' does not have the field '" + property + "'.");
        }

        return descriptor;
    }

    @Override
    public Object getValue(ELContext context, Object base, Object property) {
        if (!isRecord(base) || property == null) {
            return null;
        }

        PropertyDescriptor descriptor = getRecordPropertyDescriptor(base, property);

        try {
            Object value = descriptor.getReadMethod().invoke(base);
            context.setPropertyResolved(base, property);
            return value;
        }
        catch (Exception e) {
            throw new ELException(e);
        }
    }

    @Override
    public Class<?> getType(ELContext context, Object base, Object property) {
        if (!isRecord(base) || property == null) {
            return null;
        }

        PropertyDescriptor descriptor = getRecordPropertyDescriptor(base, property);
        context.setPropertyResolved(true);
        return descriptor.getPropertyType();
    }

    @Override
    public Class<?> getCommonPropertyType(ELContext context, Object base) {
        if (!isRecord(base)) {
            return null;
        }

        return String.class;
    }

    @Override
    public boolean isReadOnly(ELContext context, Object base, Object property) {
        if (!isRecord(base)) {
            return false;
        }

        getRecordPropertyDescriptor(base, property); // Forces PropertyNotFoundException if necessary.
        context.setPropertyResolved(true);
        return true;
    }

    @Override
    public void setValue(ELContext context, Object base, Object property, Object value) {
        if (!isRecord(base)) {
            return;
        }

        throw new PropertyNotWritableException("Java Records are immutable");
    }

    @Override
    public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object base) {
        if (!isRecord(base)) {
            return null;
        }

        Map rawDescriptors = getRecordPropertyDescriptors(base);
        return rawDescriptors.values().iterator();
    }

}
Run Code Online (Sandbox Code Playgroud)

为了让它工作,在faces-config.xml下面注册它:

<application>
    <el-resolver>com.example.RecordELResolver</el-resolver>
</application>
Run Code Online (Sandbox Code Playgroud)

真正的工作是在getValue()方法中完成的。它基本上定位java.lang.reflect.Method代表 Java 记录的访问者并调用它。

也就是说,Java Record 不适合替代完整的 JavaBean,主要是因为 Java Records 是不可变的。因此它们不能用作真正的 (JPA) 实体,因为它们应该是可变的。Java 记录最多用作 DTO。