Created
March 21, 2013 10:36
-
-
Save elaatifi/5212119 to your computer and use it in GitHub Desktop.
Example of a class-map builder supporting custom annotations to configure Orika mapper.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
AnnotationClassMapBuilder extends the default class map builder and override byDefault method to lookup for more metadata | |
*/ | |
public class AnnotationClassMapBuilder<A, B> extends ClassMapBuilder<A, B> { | |
protected AnnotationClassMapBuilder(Type<A> aType, Type<B> bType, PropertyResolverStrategy propertyResolver, | |
DefaultFieldMapper[] defaults) { | |
super(aType, bType, propertyResolver, defaults); | |
} | |
@Override | |
public ClassMapBuilder<A, B> byDefault(DefaultFieldMapper... withDefaults) { | |
Type<?> type = getAType(); | |
boolean mappedIsA = true; | |
Mapped mapped = type.getRawType().getAnnotation(Mapped.class); | |
if (mapped == null) { | |
type = getBType(); | |
mapped = getBType().getRawType().getAnnotation(Mapped.class); | |
mappedIsA = false; | |
} | |
if (mapped != null) { | |
for (Field field : type.getRawType().getFields()) { | |
Skip skip = field.getAnnotation(Skip.class); | |
if (skip != null) { | |
fieldMap(field.getName()).exclude().add(); | |
continue; | |
} | |
Copy copy = field.getAnnotation(Copy.class); | |
if (copy != null) { | |
FieldMapBuilder<A, B> fieldMap = mappedIsA ? fieldMap(field.getName(), copy.value()) : fieldMap(copy.value(), | |
field.getName()); | |
if (!"".equals(copy.converterId())) { | |
fieldMap.converter(copy.converterId()); | |
} | |
if (copy.writeOnly()) | |
fieldMap.bToA(); | |
fieldMap.add(); | |
} | |
} | |
if (mapped.byDefault()) | |
super.byDefault(withDefaults); | |
} else { | |
super.byDefault(withDefaults); | |
} | |
return this; | |
} | |
public static class Factory extends ClassMapBuilderFactory { | |
@Override | |
protected <A, B> ClassMapBuilder<A, B> newClassMapBuilder(Type<A> aType, Type<B> bType, PropertyResolverStrategy propertyResolver, | |
DefaultFieldMapper[] defaults) { | |
return new AnnotationClassMapBuilder<A, B>(aType, bType, propertyResolver, defaults); | |
} | |
} | |
} | |
/* | |
Example of Annotations | |
*/ | |
@Retention(RetentionPolicy.RUNTIME) | |
public @interface Copy { | |
String value(); | |
String converterId() default ""; | |
boolean writeOnly() default false; | |
} | |
@Retention(RetentionPolicy.RUNTIME) | |
public @interface Mapped { | |
boolean byDefault() default true; | |
} | |
@Retention(RetentionPolicy.RUNTIME) | |
public @interface Skip { | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment