I am using JAXB to create Java objects from XSD file. I am creating immutable wrappers to conceal objects generated by JAXB (earlier I was updating JAXB objects to implement immutable interface and return interface to client. But realised it is bad to change auto generated classes, hence using wrappers)
Currently I am returning these immutable wrappers to client app. Is there any option so that auto generated classes will be immutable and it will avoid extra work of creating immutable wrappers. Any other approach is encouraged.
- Thanks
You can create a Proxy for your beans just before returning them to the client. You will need javassist to create Proxies from classes (create proxies from interfaces can be done with Java SE directly).
Then, you can throw an exception if methods starting with “set” are invoked.
Here is a reusable class with a method that can wrap “any” POJO:
And here is an example code. Let Employee be your bean:
And here a test case showing that you can create a proxy for a POJO, use its getters, but you can’t use its setters