简体   繁体   中英

How to make Data lombok return deep copys of getter method

Spotbugs is giving the following Error warnings:

[ERROR] Medium: MetaData.getCreatedAt() may expose internal representation by returning MetaData.createdAt [...MetaData] At MetaData.java:[line 21] EI_EXPOSE_REP

To solve this i think i have to return a deep copy of the "createdAt".

Is there a solution to solve this directly with @Data?

No, there is none. The reason is that creating a defensive copy is different for each class, and the best way to do so depends on your use case. Lombok cannot know what you want or need.

For example, consider a mutable class with a modifiable list as a field, ie the list contents may change concurrently with the getList() call. In some cases, it could be reasonable to return a Collections.unmodifiableList() that will reflect the changes to the list that may concurrently occur. In other cases it may be better to return a list that never changes, eg creating a true copy of the list by List.copyOf() . Furthermore, if the objects in the list are also mutable, you may want to clone/copy those, too.

So if you want to return a defensive copy, you have to implement the getter manually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM