Jul 14 2008
∞
ゆの in Java feat. AspectJ
ゆの in Javaが@t_yanoさん版で紹介してもらったりゆの in Javaにみるアイデアの連鎖で元祖認定を貰ったり経緯をまとめてもらったりしてうれしい限りなんですが、 このままではただのアイデアマンで終わってしまう!と言う事で、ズルせずにちゃんと変態版を作ってみました。
ゆの in Groovyまでやっておいてちゃんとしたのを作らないと、GroovyメインでJavaは仕事用に仕方なく使ってる人みたいですし…
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
public class ゆのinJava {
@Retention(RUNTIME)
public @interface xl_lx {
String[] value();
}
@Aspect
public static class PrintAspect {
Map<Field, Integer> accessCounter = new HashMap<Field, Integer>();
int count(Field field) {
if (accessCounter.containsKey(field)) {
accessCounter.put(field, accessCounter.get(field) + 1);
} else {
accessCounter.put(field, 0);
}
return accessCounter.get(field);
}
@Before("within(ゆのinJava)&&get(@xl_lx static int ゆのinJava.*)")
public void printAspect(JoinPoint thisJoinPoint) {
Signature signature = thisJoinPoint.getStaticPart().getSignature();
String fieldName = signature.getName();
try {
Field field = ゆのinJava.class.getDeclaredField(fieldName);
xl_lx annotation = field.getAnnotation(xl_lx.class);
int count = count(field);
System.out.print(annotation.value().length <= count
? field.getName() + "!¥n" : annotation.value()[count]);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
@xl_lx( { "ひだまり", "x365 " })
static int X = 1;
@xl_lx("スケッチ")
static int _ = 1;
@xl_lx({})
static int 来週も見てくださいね = 1;
public static void main(String[] args) {
new Object() {boolean doIt() {return
X / _ / X < 来週も見てくださいね;
}}.doIt();
}
}
Aspectを使ってAnnotationに書いたのを出力する、と言うのは元々思いついてたんですけど、実家でgdgdしたり(着手時点では)前人未到だった「ゆの in Groovy」にうつつをぬかしていた関係でなかなか着手してませんでした^^;
ゆの in language って「変態の極みに挑戦する楽しさ」というほかに、便利だけど普段あんまり使わない機能を凝集して、濃いサンプル化させる、と言う楽しみも有るんだなぁ、と思い至った次第。
でも、この一連の「ゆの in なんちゃら」元祖とはズレてるかも…^^;