1
votes

I'm trying to do object properties mapping from a java bean to a non-bean POJO (a third party library object with no setters). Observing the source code, object mappers libraries out there relies on setters method for property value sets.

My question is: is there a library that wraps such non-bean POJO into a JavaBean? ( essentially generate setters and getters for all the fields and use reflection to properly setAccessible(true) of non-public fields, etc. ), such that I can map properties into the generated JavaBean, And once all its fields get populated, I can extract/convert back the underlying non-bean POJO out of it?

I decided to use JDTO as my object mapping library of choice.

Thanks in advance!

2
If there are no setters, it's probably for good reasons. The author of the class want the object to be immutable, and.or thread-safe, or want to maintain some invariants by not setting properties one by one. You're breaking encapsulation by accessing its private fields by reflection, and expose yourself to failures when youy adopt the next version of the library. COnsider copying the state to other objects instead of modifying the properl--encapsulated ones.JB Nizet

2 Answers

1
votes

You could wrap the instance of the immutable class in a dynamic proxy (java.lang.reflection.InvocationHandler). The proxy in turn could use reflection to provide the operations you like. Apache Beanutils could help here, and Hibernate uses CGLIB to speed this up.

There might be a use case for this like fixing an error in the third party library, but that's rare. If that's the case, aspectj with its interceptors could be helpful as well.

So the recommended way is to copy the values from the instance of the immutable class into another instance of a mutable one, change the state there, and then to persist it somehow "the official" way. The reasons for doing it this way are already described in JB Nizet's excellent comment, so he deserves the credit for that.

1
votes

Observing the source code, object mappers libraries out there relies on setters method for property value sets.

Well, it depends on library. If you mean Apache Beanutils, they are very conservative, they require exact type match for getter and setter, using isField convention only for primitive boolean type etc. Dozer is less restrictive, but the version I've worked with (this was about 5 year ago, however), didn't process returning settern (for chain setter model).

Instead of fighting with restrictive tools, I'd recommend you to fork and modify existing tools. The mentioned Apache Beanutils have licence allowing that, and Apache code is generally quite readable and easy to modify. You can then implement reading from public field directly, setting the fields via constructor, and if Java Security settings allow that, directly access private members (it will probably not work on most application servers, which sets the security flags to forbid that).