フレームワーク層などでリフレクションを使っていて、Javaのバージョンを1.6から上げる場合は挙動の違いに要注意
確認環境
MacOS X(10.9.5)
jdk1.6.0_65(MacOS付属のjdk)
jdk1.7.0_71
jdk1.8.0_25
サンプルコード
public abstract class Parent {
public abstract Number someMethod();
}
public class Child extends Parent {
@Override
@Sample
public Integer someMethod() {
return 1;
}
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Sample {
}
public class CheckHasSampleAnnotation {
public static void main(String[] args) {
for (Method method : Child.class.getMethods()) {
Sample annotation = method.getAnnotation(Sample.class);
if(annotation != null) {
System.out.println("----- [" + method + "] has @Sample. -----");
} else {
System.out.println("[" + method + "] doesn't have @Sample.");
}
}
}
}
出力結果
Java1.6
----- [public java.lang.Integer Child.someMethod()] has @Sample. -----
[public java.lang.Number Child.someMethod()] doesn't have @Sample.
[public final void java.lang.Object.wait() throws java.lang.InterruptedException] doesn't have @Sample.
[public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException] doesn't have @Sample.
[public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException] doesn't have @Sample.
[public boolean java.lang.Object.equals(java.lang.Object)] doesn't have @Sample.
[public java.lang.String java.lang.Object.toString()] doesn't have @Sample.
[public native int java.lang.Object.hashCode()] doesn't have @Sample.
[public final native java.lang.Class java.lang.Object.getClass()] doesn't have @Sample.
[public final native void java.lang.Object.notify()] doesn't have @Sample.
[public final native void java.lang.Object.notifyAll()] doesn't have @Sample.
Java1.7, 1.8
----- [public java.lang.Integer Child.someMethod()] has @Sample. -----
----- [public java.lang.Number Child.someMethod()] has @Sample. -----
[public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException] doesn't have @Sample.
[public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException] doesn't have @Sample.
[public final void java.lang.Object.wait() throws java.lang.InterruptedException] doesn't have @Sample.
[public boolean java.lang.Object.equals(java.lang.Object)] doesn't have @Sample.
[public java.lang.String java.lang.Object.toString()] doesn't have @Sample.
[public native int java.lang.Object.hashCode()] doesn't have @Sample.
[public final native java.lang.Class java.lang.Object.getClass()] doesn't have @Sample.
[public final native void java.lang.Object.notify()] doesn't have @Sample.
[public final native void java.lang.Object.notifyAll()] doesn't have @Sample.