今さら、ただのアノテーション使うサンプル。
(Google guice もAOP も使ってないただのサンプル)
このサンプルを手軽でなくて複雑だと言う人がいるかもしれない。
しかし、最近、これが単純で魅力的なことに思えてならない。
メソッドに付与するアノテーション
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Color{
String value();
}
-------------------------------------------------------
インターフェース
public interface IFoo{
public String parse(int i);
}
-------------------------------------------------------
インターフェースで定義したメソッドを抽象クラスの段階で、
final 宣言で実装させてしまうのがポイント
抽象メソッドを定義して、具象クラス先でそのメソッドに付与
されるアノテーションを取得して具象クラでのアノテーション値を求める。
アノテーション値の結果で抽象メソッドを実行する
public abstract class FooBase implements IFoo{
protected abstract String doParse(String s);
@Override
public final String parse(int i){
try{
Color c = this.getClass().getDeclaredMethod("doParse",new Class[]{String.class})
.getAnnotation(Color.class);
return doParse(c.value().toUpperCase() +"_"+Integer.toString(i*10));
}catch(SecurityException e){
throw new RuntimeException(e.getMessage(),e);
}catch(NoSuchMethodException e){
throw new RuntimeException(e.getMessage(),e);
}
}
}
-------------------------------------------------------
FooBase の具象クラス例
public class Foo extends FooBase{
@Color("Blue")
@Override
protected String doParse(String s){
return "doParse result = "+s;
}
}
-------------------------------------------------------
実行は、、、
IFoo f = new Foo();
String s = f.parse(20);
System.out.prinln(s);
ここで、IFoo の実行メソッドでparseしか見えないのが良い
Colorアノテーションの処理は、継承元にお任せなのが良い。
結果の標準出力、、、
doParse result = BLUE_200