[Simple-support] TransformMatcher
Brought to you by:
niallg
|
From: Fabian K. <fab...@we...> - 2009-04-12 14:11:23
|
Hi List,
I created two classes which could be useful for others aswell:
First, an Annotation:
/**
* Use this annotation to indicate that your class can be transformed.
*
* @author Fabian Kürten
* @version 0.1
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface Transformable {
/**
* The transformers type.
*
* @return the type
*/
public Class<? extends Transform<?>> type();
}
And second, the TransformMatcher:
/**
* This Matcher looks for the {@link Transformable} annotation to create a
* suitable {@link Transform}.
*
* @see Transformable
* @author Fabian Kürten
* @version 0.1
*/
public class TransformMatcher
implements
Matcher {
private final Matcher delegate;
/**
* Creates the Matcher.
*/
public TransformMatcher() {
this.delegate = null;
}
/**
* Creates the Matcher with a delegate Matcher.
*
* @param delegate the delegate will be called if no match could be found
*/
public TransformMatcher(Matcher delegate) {
this.delegate = delegate;
}
public Transform match(Class type) throws Exception {
Class<?> type2 = type;
Transformable t = type2.getAnnotation(Transformable.class);
if (t != null) {
Class<?> transformerClass = t.type();
Transform<?> transformer = (Transform<?>) transformerClass.newInstance();
return transformer;
} // t != null
if (this.delegate != null) {
return this.delegate.match(type);
} else {
return null;
}
}
}
The usage is quite simple, you have to use the Matcher of course:
Serializer serializer = new Persister(new TransformMatcher());
and annotate your class:
@Root
@Transformable(type=full.package.name.MyTransform.class)
public final class MyClass
I hope someone finds this useful.
Fabian
|