Suppose I have a DTO class:
public class SomeImmutableDto {
private final String someField;
private final String someOtherField;
public SomeImmutableDto(String someField, String someOtherField) {
// field setting here
}
// getters here
}
This is a nice immutable DTO. But what if I have 20 fields? It leads to the proliferation of a lot of unreadable constructors and unmaintainable code.
There is a solution for this problem however, the Builder pattern:
public class SomeImmutableDto {
private final String someField;
private final String someOtherField;
private SomeImmutableDto(Builder builder) {
// field setting here
}
public static class Builder {
private String someField;
private String someOtherField;
// setters here
public SomeImmutableDto build() {
// building code here
}
}
// getters here
}
Now I can do something like this:
SomeImmutableDto dto = new SomeImmutableDto.Builder()
.setSomeField(/* ... */)
*setSomeOtherField(/* ... */)
.build();
Now I have an immutable dto which does not have an abundance of ugly constructors.
My problem is that I need a dto which has public setters AND immutable because there are some legacy code in the project which cannot be refactored at the moment and it requires the presence of public setters in order to initialize dto objects.
Is there some pattern which is usable here or this won't work? I'm thinking about the Proxy pattern but I'm not sure it can be applied in a way it is not looking like an ugly hack.
I think if you need to be legacy-code-compliant, the best way is to use a non modifiable wrapper just like in Collections.unmodifiableList method it is done.
It is "hack", but I think it is forced by legacy code and it is "not so bad" :)
Related
Foo foo = Foo.builder()
.setColor(red)
.setName("Fred")
.setSize(42)
.build();
So I know there is the following "Builder" solution for creating named parameters when calling a method. Although, this only seems to work with inner static classes as the builder or am I wrong? I had a look at some tutorials for builder pattern but they seem really complex for what im trying to do. Is there any way to keep the Foo class and Builder class separate while having the benefit of named parameters like the code above?
Below a typical setup:
public class Foo {
public static class Builder {
public Foo build() {
return new Foo(this);
}
public Builder setSize(int size) {
this.size = size;
return this;
}
public Builder setColor(Color color) {
this.color = color;
return this;
}
public Builder setName(String name) {
this.name = name;
return this;
}
// you can set defaults for these here
private int size;
private Color color;
private String name;
}
public static Builder builder() {
return new Builder();
}
private Foo(Builder builder) {
size = builder.size;
color = builder.color;
name = builder.name;
}
private final int size;
private final Color color;
private final String name;
}
Use composition. To make things easier and cleaner, do not replicate all attributes in source (Foo) and builder (Builder) class.
For example, have Foo class inside Builder instead of each of Foo attribute.
simple code snippet:
import java.util.*;
class UserBasicInfo{
String nickName;
String birthDate;
String gender;
public UserBasicInfo(String name,String date,String gender){
this.nickName = name;
this.birthDate = date;
this.gender = gender;
}
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append("Name:DOB:Gender:").append(nickName).append(":").append(birthDate).append(":").
append(gender);
return sb.toString();
}
}
class ContactInfo{
String eMail;
String mobileHome;
String mobileWork;
public ContactInfo(String mail, String homeNo, String mobileOff){
this.eMail = mail;
this.mobileHome = homeNo;
this.mobileWork = mobileOff;
}
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append("email:mobile(H):mobile(W):").append(eMail).append(":").append(mobileHome).append(":").append(mobileWork);
return sb.toString();
}
}
class FaceBookUser {
String userName;
UserBasicInfo userInfo;
ContactInfo contactInfo;
public FaceBookUser(String uName){
this.userName = uName;
}
public void setUserBasicInfo(UserBasicInfo info){
this.userInfo = info;
}
public void setContactInfo(ContactInfo info){
this.contactInfo = info;
}
public String getUserName(){
return userName;
}
public UserBasicInfo getUserBasicInfo(){
return userInfo;
}
public ContactInfo getContactInfo(){
return contactInfo;
}
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append("|User|").append(userName).append("|UserInfo|").append(userInfo).append("|ContactInfo|").append(contactInfo);
return sb.toString();
}
static class FaceBookUserBuilder{
FaceBookUser user;
public FaceBookUserBuilder(String userName){
this.user = new FaceBookUser(userName);
}
public FaceBookUserBuilder setUserBasicInfo(UserBasicInfo info){
user.setUserBasicInfo(info);
return this;
}
public FaceBookUserBuilder setContactInfo(ContactInfo info){
user.setContactInfo(info);
return this;
}
public FaceBookUser build(){
return user;
}
}
}
public class BuilderPattern{
public static void main(String args[]){
FaceBookUser fbUser1 = new FaceBookUser.FaceBookUserBuilder("Ravindra").build(); // Mandatory parameters
UserBasicInfo info = new UserBasicInfo("sunrise","25-May-1975","M");
// Build User name + Optional Basic Info
FaceBookUser fbUser2 = new FaceBookUser.FaceBookUserBuilder("Ravindra").
setUserBasicInfo(info).build();
// Build User name + Optional Basic Info + Optional Contact Info
ContactInfo cInfo = new ContactInfo("xxx#xyz.com","1111111111","2222222222");
FaceBookUser fbUser3 = new FaceBookUser.FaceBookUserBuilder("Ravindra").
setUserBasicInfo(info).
setContactInfo(cInfo).build();
System.out.println("Facebook user 1:"+fbUser1);
System.out.println("Facebook user 2:"+fbUser2);
System.out.println("Facebook user 3:"+fbUser3);
}
}
output:
Facebook user 1:|User|Ravindra|UserInfo|null|ContactInfo|null
Facebook user 2:|User|Ravindra|UserInfo|Name:DOB:Gender:sunrise:25-May-1975:M|ContactInfo|null
Facebook user 3:|User|Ravindra|UserInfo|Name:DOB:Gender:sunrise:25-May-1975:M|ContactInfo|email:mobile(H):mobile(W):xxx#xyz.com:1111111111:2222222222
Explanation:
FaceBookUser is a complex object with below attributes using composition:
String userName;
UserBasicInfo userInfo;
ContactInfo contactInfo;
FaceBookUserBuilder is a static builder class, which contains and builds FaceBookUser.
userName is only Mandatory parameter to build FaceBookUser
FaceBookUserBuilder builds FaceBookUser by setting optional parameters : UserBasicInfo and ContactInfo
This example illustrates three different FaceBookUsers with different attributes, built from Builder.
fbUser1 was built as FaceBookUser with userName attribute only
fbUser2 was built as FaceBookUser with userName and UserBasicInfo
fbUser3 was built as FaceBookUser with userName,UserBasicInfo and ContactInfo
In this example, composition has been used instead of duplicating all attributes of FaceBookUser in Builder class.
EDIT:
Group all related attributes into logical classes. Define all these classes in FaceBookUser. Instead of adding all these member variables again in Builder, contain FaceBookUser in Builder class.
For simplicity, I have added two classes: UserBasicInfo and ContactInfo . Now explode this FaceBookUser class with other attributes like
NewsFeed
Messages
Friends
Albums
Events
Games
Pages
Ads
etc.
If you duplicate all these attributes in both Builder and FaceBookUser, code will become difficult to manage. Instead, by using composition of FaceBookUser in FaceBookUserBuilder itself, you can simply construction process.
Once you add above attributes, you will build FaceBookUser in step-by-step process as usual.
It will be like this:
FaceBookUser fbUser3 = new FaceBookUser.FaceBookUserBuilder("Ravindra").
setUserBasicInfo(info).
setNewsFeed(newsFeed).
setMessages(messages).
setFriends(friends).
setAlbums(albums).
setEvents(events).
setGames(games).
setAds(ads).build();
You can sure change the fields of your Builder class to be private - then you just need a (public) getter method for each "property" on the builder; and the constructor in Foo calls those methods; instead of just fetching the fields in the Builder object.
Then you can just move your Builder class out of Foo. Simple and straightforward.
But keep in mind: in the end, Builder and Foo are very closely related. They share a common set of fields by design. So any change to Foo affects Builder; and vice versa. Thus it makes a lot of sense to keep them "close together". Maybe not as inner/outer class, but maybe still within the same source file! But then ... only one of them can be public. Is that really what you want?!
In other words: don't rip things apart just "because you can". Only do it if you have good reasons to do so, and if the thing that comes out of that is better than your current solution!
Edit: your problem might not be separation of Foo and Builder, but the fact that your Foo class has too many fields in the first place. Dont forget about the single responsibility principle ... when your class needs more than 5, 6 fields ... it is probably doing too much and should be further sliced! Keep in mind: good OO design is first of all about behavior; not about having 10, 20 fields within some object!
It's difficult to strictly define "The Builder Pattern™", and there are several degrees of freedom regarding the design choices. Some concepts can easily be mixed or abused, and beyond that, it is generally hard (and nearly always wrong) to say "you always have to do it exactly like that".
The question is what should be achieved by applying a "pattern". In your question and the example, you already mixed two concepts, namely the builder pattern and the fluent interface. Playing devil's advocate, one could even sneakily argue that the "Builder" in your case is just the Parameter Object that Thomas already mentioned, which is constructed in a special way (fluently) and enriched with some tricky combination of public and private visibilities.
Some of the possible goals of the builder pattern are overlapping or go hand in hand. But you should ask yourself what the primary goal is in your case:
Should the resulting object be immutable?
Should it be really immutable, with only final final fields, or could there also be setters that just should not be public? (The builder could still call these non-public setters!)
Is the goal to limit visibility in general?
Should there be polymorphic instantiation?
Is the main goal to summarize a large number of constructor parameters?
Is the main goal to offer an easy configuration with a fluent interface, and to manage "default" values?
...
As all these question will have an effect on the subtle differences in the design. However, regarding your actual, high level, "syntactic" question:
You could design the builder as a public static inner class (what you did in the example).
public class Person {
...
public static PersonBuilder create() { ... }
public static class PersonBuilder {
...
public Person build() { ... }
}
}
This offers the strictest form of privacy: The constructors of Person and PersonBuilder may both be private.
You could also place the actual class and its builder in separate files:
public class Person {
...
}
and
public class PersonBuilder {
...
}
A reasonable degree of privacy can be achieved here: The constructors of both can be package private (i.e. have default visibility).
In both cases, the actual usage for clients would be the same, except for the name of the builder class (package.Person.PersonBuilder vs. package.PersonBuilder). The "contents" of the classes would also be the same (except for slightly different visibilities). And in both cases, you can create subclasses of Person, if desired, depending on the builder configuration, and the builder itself can have a fluent interface.
As an alternative to the builder pattern, you could also use a parameter object:
class FooParams {
public int size;
public Color color;
public String name;
}
You can use getters and setters here, instead of public fields, if you prefer.
Then the Foo constructor takes one of these as an argument:
public Foo(FooParams params) {
this.size = params.size;
this.color = params.color;
this.name = params.name;
}
I want to serialize a POJO class which is not under my control, but want to avoid serializing any of the properties which are coming from the superclass, and not from the final class. Example:
public class MyGeneratedRecord extends org.jooq.impl.UpdatableRecordImpl<...>,
example.generated.tables.interfaces.IMyGenerated {
public void setField1(...);
public Integer getField1();
public void setField2(...);
public Integer getField2();
...
}
You can guess from the example that that this class is generated by JOOQ, and inherits from a complex base class UpdatableRecordImpl which also has some bean property-like methods, which cause problems during the serialization. Also, I have several similar classes, so it would be good to avoid duplicating the same solution for all of my generated POJOs.
I have found the following possible solutions so far:
ignore the specific fields coming from superclass using mixin technique like this: How can I tell jackson to ignore a property for which I don't have control over the source code?
The problem with this is that if the base class changes (e.g., a new getAnything() method appears in it), it can break my implementation.
implement a custom serializer and handle the issue there. This seems a bit overkill to me.
as incidentally I have an interface which describes exactly the properties I want to serialize, maybe I can mixin a #JsonSerialize(as=IMyGenerated.class) annotation...? Can I use this for my purpose?
But, from pure design point of view, the best would be to be able to tell jackson that I want to serialize only the final class' properties, and ignore all the inherited ones. Is there a way to do that?
Thanks in advance.
You can register a custom Jackson annotation intropector which would ignore all the properties that come from the certain super type. Here is an example:
public class JacksonIgnoreInherited {
public static class Base {
public final String field1;
public Base(final String field1) {
this.field1 = field1;
}
}
public static class Bean extends Base {
public final String field2;
public Bean(final String field1, final String field2) {
super(field1);
this.field2 = field2;
}
}
private static class IgnoreInheritedIntrospector extends JacksonAnnotationIntrospector {
#Override
public boolean hasIgnoreMarker(final AnnotatedMember m) {
return m.getDeclaringClass() == Base.class || super.hasIgnoreMarker(m);
}
}
public static void main(String[] args) throws JsonProcessingException {
final ObjectMapper mapper = new ObjectMapper();
mapper.setAnnotationIntrospector(new IgnoreInheritedIntrospector());
final Bean bean = new Bean("a", "b");
System.out.println(mapper
.writerWithDefaultPrettyPrinter()
.writeValueAsString(bean));
}
}
Output:
{
"field2" : "b"
}
You can override the superclass' methods which you'd like to prevent from being output and annotate them with #JsonIgnore. The override shifts the control of property creation to the subclass while enabling its ability to filter it from the output.
For instance:
public class SomeClass {
public void setField1(...);
public Integer getField1();
public void setField2(...);
public Integer getField2();
#Override
#JsonIgnore
public String superClassField1(...){
return super.superClassField1();
};
#Override
#JsonIgnore
public String superClassField2(...){
return super.superClassField2();
};
...
}
You can use this as well instead of unnecessary overrides
#JsonIgnoreProperties({ "aFieldFromSuperClass"})
public class Child extends Base {
private String id;
private String name;
private String category;
}
The good use of inheritance is that the child classes extend or add functionality. So the usual way is to serialize the data.
A workarround would be to use a Value Object (VO) or Data Transfer Object (DTO) with the fields you need to serialize. Steps:
Create a VO class with the fields that should be serialized.
Use BeanUtils.copyProperties(target VO, source data) to copy the properties
Serialize the VO instance.
Add the following annotation in your Base Class :
#JsonInclude(Include.NON_NULL)
I am extending a class to store some extra fields that I need to my application, but the class I am extending has no setter methods, and just a default constructor.
http://restfb.com/javadoc/com/restfb/types/Post.html#Post()
I am using a framework that requires the getters to be in a correct naming format as the fields in the type. However, as I cannot set the fields from the constructor, or from setters, I have kept a local copy of the initial object that I wish to store in my new object.
I then have overridden the methods to pull the data from the initial object as follows:
#Override
public String getMessage() {
return initialPost.getMessage();
}
This does not seem like a good way to do things, one annoying reason being that I would have to override every method if I wish to use all fields.
What is the best way to solve this issue? Would this be a use case for composition over inheritance?
I think I may have tried to combine both here, which seems incorrect!
public class MyPost extends Post{
private String postId;
private Post initialPost;
private PostType type;
private Brand brand;
private Product product;
private List<Photo.Image> postImages;
Thanks for all advice.
You indeed combined both composition and inheritance; which is a pretty confusing situation. I would go with inheritance since you are extending the behaviour of an object with a more specific purpose to just that object.
This also solves your problem because a public method from the Post class is also available as a public method from its subclasses (and as such, the framework can happily use getMessage() without you having to redefine it).
From my comment below:
Post is essentially an immutable object so it is not intended to be constructed by you. You could override the methods from Post in MyPost and add your own getters/setters, but you should reflect whether or not this is an approach you want to take.
An example of how you would implement this:
class Post {
private String body;
public String getBody() {
return body;
}
}
class MyPost extends Post {
private String body;
public void setBody(String body) {
this.body = body;
}
#Override
public String getBody() {
return body;
}
}
Now the getBody() method from the Post class is overridden by the selfdefined one from MyPost.
I am learning about the builder pattern, and so far I understood that, it is a great alternative to the commonly patterns used for initialization:
Telescoping Constructor Pattern
JavaBean Pattern
The thing is, I don't really like to remove the getters and setters from the objects in my domain model. I always like to keep them as POJOs. One of the reasons I don't like it is:
If i don't use POJOs, then it is not easy to annotate the variables when using ORM frameworks...
So here are my doubts:
-Is it possible to implement the builder pattern without using static inner classes?
-If I have to use the builder pattern by using the inner class, do you think it is correct to keep the getters and the setters?
-I did a little example for practice where I tried to avoid the inner class.
Could you let me what do you think about it?
Product
public class Product
{
private String color;
private int price;
public Product() {
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String toString() {
return getColor() + "\n" + getPrice();
}
}
Builder
public class Builder
{
private Product product;
public Builder() {
product = new Product();
}
public Builder withColor(String color) {
product.setColor(color);
return this;
}
public Builder withPrice(int price) {
product.setPrice(price);
return this;
}
public Product build() {
return product;
}
}**
Client
public class Client
{
public static void main(String[] args) {
System.out.println(new Builder().withColor("Black").withPrice(11).build());
System.out.println("-----------------------------------------------------");
System.out.println(new Builder().withColor("Blue").withPrice(12).build());
}
}
The Builder pattern is useful to create immutable objects and avoid several constructors with optional parameters.
IMO using Builder pattern to build a POJO which can be updated using setters is useless. You only create an additional class.
Depending on the ORM framework used, it might not need the presence of setter method. But only assigning members values through reflection.
Product class:
public final class Product {
private final String color;
private final int price;
public Product(Builder builder) {
this.color = builder.getColor();
this.price = builder.getPrice();
}
public String getColor() {
return color;
}
public int getPrice() {
return price;
}
public String toString() {
return getColor() + "\n" + getPrice();
}
}
Builder class:
public final class Builder {
private String color;
private int price;
public Builder() {
// Assign any default values
}
public Builder color(String color) {
this.color = color;
return this;
}
public Builder price(int price) {
this.price = price;
return this;
}
protected String getColor() {
return color;
}
protected int getPrice() {
return price;
}
public Product build() {
return new Product(this);
}
}
The builder pattern is most useful in the context of immutable objects. Immutable objects don't have setters by definition. So all of their properties have to be squeezed into the constructor. This is where the builder pattern comes in handy. It allows you to split the initialization of a complex immutable object into multiple, self-explaining instructions so you don't need to have constructor calls like this fictional example all over you code where you can't tell which argument does what:
Thing foo = new Thing(1, 125, Thing.SOMETHING, new Whatchamacallit(17, 676), getStuffManager(StuffManager.ZOMG), true, false, false, maybe);
I don't find that the Builder pattern creates any signficant value when the created object is mutable. Everything you do through the builder can also be done with the created object directly.
Also, I think that your program above is not a textbook example of the builder pattern. You usually don't create an object by passing the builder to the constructor. You create an object by calling a create method on the builder which then passes all its properties to the constructor of the object. This pattern has the advantage that it gives the builder the opportunity to check its internal state for consistency and maybe throw an exception before starting to build the object.
The java StringBuilder class is a good example (the create method being tostring in this case).
What does using a builder here actually gain you?
Nothing as far as I can see: you could just create a new Product and use the getters and setters on it directly. If you have a simple POJO then there is absolutely nothing wrong with:
Product p=new Product();
p.setColour("Black");
p.setPrice(11);
doSomethingWith(p);
Saving a few characters of typing is IMHO not worth introducing a new class / builder abstraction.
Builders are more useful in situations like the following:
You want to create an immutable object (and hence can't use setters)
If you have complicated factory logic that cannot easily be expressed with simple getters and setters or that you want to re-use in different ways
(Occasionally) when you want to have different parts of the code base configure different aspects of the builder for some reason.
The builder pattern lends itself well to producing immutable classes, but it can still be a good option for mutable classes too.
A builder is a reasonable design choice in any situation where an object contains many fields that need to be set during construction; particularly if sensible defaults can be chosen for several of the values.
Whether you use an inner class depends upon your goals. If you wish to force construction through the builder, you can define the builder as an inner class and ensure the outer class only has a private constructor.
Here are Builder collaborations from GoF book:
Collaborations
1. The client creates the Director object and configures it with the desired Builder object.
2. Director notifies the builder whenever a part of the product should be built.
3. Builder handles requests from the director and adds parts to the product.
3. The client retrieves the product from the builder.
The Builder pattern focuses on constructing a complex object step by step. Builder returns the product as a final step. The returned class in absence of the setters may be as good as immutable. With setters, it can be modified. And inner classes help mask the details.
Another point worth noting is that a major motivation behind creational design patterns is that the client doesn't worry about creating the product. The object creation process is delegated to factory, builder, etc. The client doesn't have to worry about object creation. It will specify what it wants and will get it as a result of delegated creation process.
Is it possible to implement the builder pattern without using static
inner classes?
Absolutely, yes. As far as the Builder design pattern is concerned, it does not make any difference if the Builder is an inner class or not.
-If I have to use the builder pattern by using the inner class, do you think it is correct to keep the getters and the setters?
Yes, it is ok. it is kind of like, build the object using a certain template and then customize it, if needed.
-I did a little example for practice where I tried to avoid the inner
class. Could you let me what do you think about it?
Two problems -
the example does not justify the usage of Builder pattern. Builder pattern is used to build a complex object. So if you can simply build product as :
Product p = new Product();
p.setColor(c);
p.setPrice(prc);
Then there is hardly any benefit in the way you have shown.
Product should not have a dependency on Builder.
I found myself thinking if getters are any good in a builder. A builder shouldn't generally be used as a return value - a single method or class should be responsible for creation of the entity using builder. Thus, the method (or class) should keep the information it needs instead of getting it back.
For those reasons, I decided not to use any getters in the builder class. Builder only has setters (be it withAbc(...), setAbc(...) or abc(...)), build() and possibly some private methods like validate().
Using class Product, a sample entity looks like this:
class Product {
private final String color;
private final int price;
private Product(ProductBuilder builder) {
this.color = builder.color;
this.price = builder.price;
}
// equals, hashCode, toString
public builder() {
return new ProductBuilder(this);
}
public static emptyBuilder() {
return new ProductBuilder();
}
public String getColor() {
return color;
}
public int getPrice() {
return price;
}
Now, a builder class is an inner class of the entity, which allows me to use private constructors.
public static class ProductBuilder {
private String color;
private int price;
private ProductBuilder() {
}
private ProductBuilder(Product entity) {
this.color = entity.color;
this.price = entity.price;
}
public ProductBuilder withColor(String color) {
this.color = color;
return this;
}
public ProductBuilder withPrice(int price) {
this.price = price;
return this;
}
public Product build() {
return new Product(this.validate());
}
private ProductBuilder validate() {
if (color == null) {
throw new IllegalStateException("color is null");
}
return this;
}
}
As you can see, I added method builder() to get builder as a copy of the instance and emptyBuilder() as a factory method to hide constructor (maybe there is a better name for it).
Also, when constructing an immutable class, make sure everything inside is immutable as well. Collections are tricky, you have to make a copy, then use Collections.unmodifiable*(...) on it to ensure nobody has a reference to the collection lying under the unmodifiable wrapper.
EDIT: Allegedly, you need getters if you have abstract superclass. That is an overstatement. You only need it if you have a constructor with all params. If you pass the builder instead, like me, you get:
class Product extends Something { ...
private Product(ProductBuilder builder) {
super(builder); // that one must be protected, not private
...
}
public static class ProductBuilder extends SomethingBuilder { ...
protected ProductBuilder validate() {
super.validate();
...
}
}
}
So, do we need getters? This time, not really. We're still fine without them. Some other ideas?
Builder is about several things and you may want to utilize only one aspect: fluent API. You may attain the best fit for your needs by just changing your setters to return this instead of void. Then you can use the chained-setter idiom: return new MyBean().setCheese(cheese).setBacon(bacon);
On a side note, the term "POJO" does not mean the same as "JavaBean". In fact, sometimes these two terms are used as opposites. The point of a POJO is that it doesn't conform to anything else than being a Java object. It may use public variables, for example.
I'm in the need of do some clean up of some invisible characters (\r\n) and html tags for specific getters on my entities.
I've been trying to use mixIns to modify what's returned from the entity but I'm not sure how can I reference the target class in my MixIn so I can add the clean up logic there. From the my tests seems that not even my method is called.
This is what I have so far, but it never gets called
public abstract class BookMixIn {
#JsonProperty
public String getTitle() {
return StringUtils.deleteWhitespace(getTitle());
}
}
public class Book {
private String title;
// getter/setters omitted...
}
And the ObjectMapper config:
mapper.getSerializationConfig().addMixInAnnotations(com.company.Book.class,
com.company.BookMixIn.class);
mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
String tmp = mapper.writeValueAsString(book);
log.info(tmp);
Can this be accomplished via MixIns?
Thanks
Jackson mix-ins are purely for associating annotations; they are not used for adding behavior (code).
So they would not help you here.
But the simple way that would work (possibly using mix-in too) is to add annotation for using custom serializer, which can use whatever filtering is needed:
#JsonSerialize(using=MyCoolSerializer.class) public String getTitle() { }
so either add that to POJO, if possible; but if not, associate it using mix-in.
If you are running Jackson 1.9, this works:
BookCleaner cleanBook = new BookCleaner(book);
mapper.getSerializationConfig().addMixInAnnotations(Book.class, BookMixIn.class);
mapper.writeValueAsString(cleanBook);
#JsonSerialize
class BookCleaner {
private Book book;
public BookCleaner(final Book book) { this.book = book; }
#JsonUnwrapped
public Book getBook() { return book; }
#JsonProperty("title")
public String getCleanTitle() { return cleanup(getBook().getTitle()); }
}
public interface BookMixIn {
#JsonIgnore public String getTitle();
}
I don't think it works like this; the class or interface is just used as a signature.
You could use AspectJ to modify the return value, but it might be easier to just create a decorator and serialize that instead of the underlying object.
Alternatively, you could create specific getters for the "safe" versions of things and use the #JsonProperty annotation to give it the name you need, and use #JsonIgnore on the "non-safe" getters.