JAVA注記例
Annotation(注記)はJDK 5.0以降のバージョンで導入されました.ドキュメントの作成、コード内の依存性の追跡、基本コンパイル時のチェックに使用できます.注釈は「@注釈名」でコードに存在し、注釈パラメータの個数に応じて、注釈をタグ注釈、単値注釈、完全注釈の3種類に分けることができます.これらはプログラムの意味に直接影響しません.注釈(識別)として存在します.反射メカニズムプログラミングによってこれらのメタデータへのアクセスを実現できます.また、コンパイル時にコード内の注釈がソースコードレベルにのみ存在するかどうか、classファイルにも表示されるかどうかを選択できます.
注釈の文法は比較的に簡単で、@記号の使用を除いて、それは基本的にjavaの固有の文法と一致して、javaは3種類の注釈を内蔵して、javaに定義します.langパッケージにあります.@Overrideは、現在のメソッドが親を上書きするメソッドであることを示します.@Deprescatedは、現在の要素が使用に賛成していないことを示します.@SuppressWarningsは、不適切なコンパイラ警告情報を閉じることを示します.
注記を定義する例を次に示します.
次に、注釈を使用して注釈を解析する例を示します.
出力結果は次のとおりです.
注釈の文法は比較的に簡単で、@記号の使用を除いて、それは基本的にjavaの固有の文法と一致して、javaは3種類の注釈を内蔵して、javaに定義します.langパッケージにあります.@Overrideは、現在のメソッドが親を上書きするメソッドであることを示します.@Deprescatedは、現在の要素が使用に賛成していないことを示します.@SuppressWarningsは、不適切なコンパイラ警告情報を閉じることを示します.
注記を定義する例を次に示します.
package com.annotation.test;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @Target,@Retention,@Documented,@Inherited
*
* @Target , ElemenetType :
* ElemenetType.CONSTRUCTOR
* ElemenetType.FIELD ( enum )
* ElemenetType.LOCAL_VARIABLE
* ElemenetType.METHOD
* ElemenetType.PACKAGE
* ElemenetType.PARAMETER
* ElemenetType.TYPE , ( ) enum
*
* @Retention 。 RetentionPolicy :
* RetentionPolicy.SOURCE
* RetentionPolicy.CLASS class , VM
* RetentionPolicy.RUNTIME VM , 。
*
* @Documented javadoc
*
* @Inherited
*
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
/**
* Test
* id description
* description "no description"
*/
public @interface TestAnnotation {
public int id();
public String content() default "no content";
}
次に、注釈を使用して注釈を解析する例を示します.
package com.annotation.test;
import java.lang.reflect.Method;
public class Test01 {
/**
*
*/
@TestAnnotation(id = 1, content = "this is method1")
public void method1() {
}
@TestAnnotation(id = 2)
public void method2() {
}
@TestAnnotation(id = 3, content = "this is method3")
public void method3() {
}
/**
* , Test01
*/
public static void main(String[] args) {
Method[] methods = Test01.class.getMethods();
for (Method m : methods) {
/**
*
*/
boolean hasAnnotation = m.isAnnotationPresent(TestAnnotation.class);
if (hasAnnotation) {
TestAnnotation annotation = m.getAnnotation(TestAnnotation.class);
System.out.println(m.getName() + " Annotation(id=" + annotation.id() + ", content=" + annotation.content() + ")");
}
}
}
}
出力結果は次のとおりです.
method1 Annotation(id=1, content=this is method1)
method2 Annotation(id=2, content=no content)
method3 Annotation(id=3, content=this is method3)