支持最终字段的Java持久性提供程序 [英] Persistence provider for Java that supports final fields

查看:53
本文介绍了支持最终字段的Java持久性提供程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Java还是很陌生,但是我已经养成了习惯,在可能的情况下使用final声明不变性,我认为这是一件好事. (考虑f#)

I'm very new to Java but I've been developing a habit to use final wherever possible declaring immutability which i think is a good thing. (Consider f#)

我已阅读到JPA不支持final字段.休眠,TopLink?我不确定这些,但是我现在更喜欢JPA.

I've read that JPA does not support final fields. Hibernate, TopLink? I'm not sure about these but i prefer JPA for now.

从理论上说(甚至通过反射)在创建后修改最终字段是否可行?我的猜测是……不:)

Is that even possible theoretically - let's say through reflection - to modify final fields after creation? My guess would be... NO :)

持久性解决方案肯定有可能是通过参数支持构造函数.至少我看不出有什么理由可以做到这一点.我想映射会有些棘手. 这是另一种解决方案.

What would be certainly possible for a persistence solution is to support constructors with parameters. At least i see no reason that would make this impossible. Mapping would be a little tricky i guess. This is an alternative solution.

建议?

编辑:我对不可变的确切定义不熟悉,因此我在这篇文章中直观地使用了它.在这里声明不可变性意味着声明一个字段不能更改.抱歉造成误会.

I'm not familiar with the exact definition for immutable so i used it in this post intuitively. Declaring Immutability here means declaring that a field cannot be changed. Sorry for the misunderstanding.

推荐答案

对象不可变性(请注意,不可变对象与声明字段final之间的区别-如果所有字段都是final,则对象是不可变的,因此对象的状态可以(创建后不会更改)是一个非常敏感的话题.我自己喜欢它们,休眠通过@Immutable支持它们.

Object immutability (note the difference between an immutable object, and declaring a field final - an object is ONLY immutable if ALL fields are final, thus the object's state can't change after creation) is a very sensitive topic. I like them myself, and hibernate supports them through @Immutable.

不知道它在JPA 2中的状态,而是回答有关最终字段的问题:您可以使用反射来更改它们的值-但是反射在Java EE环境中受到严重限制.

Don't know about it's status in JPA 2, but to answer the question about final fields: you CAN change their values using reflection - but reflection is severly limited in a Java EE environment.

要启发一个主要问题:如果您的POJO是不可变的,那么持久性解决方案将如何重新创建对象?假设您有两个最终的int字段,以及一个用于初始化它们的构造函数.持久层不能包含有关其顺序或名称的任何信息(因为在编译过程中会删除字段和参数名称).

To enlighten the main problem: if your POJOs are immutable, then how would a persistent solution recreate the objects? Let's say you have two final int fields, and a constructor to initialize them. The persistence layer cannot have any information about their order, or their names (as field and parameter names are erased during compiling).

Koshuke发布了一个有关此的博客(关于支持不可变bean的JAXB),但是现在找不到.

Koshuke posted a blog about this (in relation to JAXB supporting immutable beans), but can't find it right now.

这篇关于支持最终字段的Java持久性提供程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆