Skip to content

Instantly share code, notes, and snippets.

@mimaun
Created May 31, 2015 09:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mimaun/4b480c0891dc131e64ee to your computer and use it in GitHub Desktop.
Save mimaun/4b480c0891dc131e64ee to your computer and use it in GitHub Desktop.
Annotationのインスタンスを取得
import java.lang.annotation.*;
/* annotationを作成 */
// Retention: 新たにアノテーションNewAnnotationを作るとき、このアノテーション情報はソースコードのみにしか保存されないことを意味する.
@Retention(RetentionPolicy.RUNTIME)
// Target: このアノテーションをどの型に使うことができるかを指定している.
@Target(ElementType.METHOD)
@interface Sweets {
boolean isHungry() default true;
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface AboutMe {
Name my_name();
}
@interface Name {
String first_name();
String last_name();
}
/* annotation 利用 */
@AboutMe(my_name=@Name(first_name="mi-kun",last_name="ese"))
public class ExampleAnnotation {
@Sweets
void test1() {
throw new RuntimeException("test1 always fail");
}
@Sweets(isHungry=false)
void test2() {
throw new RuntimeException("this should not be called");
}
}
import java.lang.annotation.*;
import java.lang.reflect.*;
public class Execute {
public static void main(String[] args) throws Exception {
// 第一引数の名前のクラスのインスタンスからアノテーションを取得する.
Annotation[] aList = Class.forName(args[0]).getAnnotations();
// アノテーションの数だけ.
for(Annotation aa: aList) {
// AboutMeアノテーションにキャスト.
AboutMe me = (AboutMe)aa;
System.out.println("print me: " + me);
System.out.println(me.my_name().first_name() + " " + me.my_name().last_name());
}
// 第一引数のクラス内のメソッドの数だけ.(publicでないものも含む.)
for(Method m: Class.forName(args[0]).getDeclaredMethods()) {
// アノテーションが存在する.
if(m.isAnnotationPresent(Sweets.class)) {
// Test Annotationのインスタンスを生成.
Sweets sweet = m.getAnnotation(Sweets.class);
try {
// 引数なしなのでinvoke(null)でmを実行.
m.invoke(null);
} catch(Throwable ex) {
System.out.print("sweet: ");
// sweetのisHungryによる.
if(sweet.isHungry()) {
System.out.println(m.getName() + " failed");
} else {
System.out.println(m.getName() + " ignored");
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment