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?
CodePudding user response:
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 instance, consider a mutable class with a modifiable list, i.e. 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, e.g. 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.