Java注釈の使用
注釈の使用は非常に簡単です。メソッドの注釈など、注釈が必要な場所を示す必要があります。
public class test {@override public string toString(){return "override it"; }}たとえば、クラスでの注釈:
@Deprecated Public Class Test {}したがって、Java組み込みの注釈は直接使用できますが、多くの場合、自分でいくつかの注釈を定義する必要があります。たとえば、一般的なスプリングでは、多数の注釈を使用して、オブジェクト間の依存関係を管理します。独自の注釈を定義する方法を見てみましょう。次のように注釈を実装します。@Testを介して特定のクラスに文字列を注入し、@TestMethodを介して文字列をメソッドに注入します。
1.テストアノテーションを作成し、クラスに行動して実行時に保持するように宣言し、デフォルト値はデフォルトです。
@target({elementType.Type})@retention(RetentionPolicy.runtime)public @interface test {string value()default "default"; } 2。testMethodアノテーションを作成し、メソッドに作用するように宣言し、実行時に保持します。
@Target({elementType.Method})@retention(RetentionPolicy.Runtime)public @interface testmethod {string value(); } 3.テストクラス、実行後、2つの文字列のデフォルトとtomcat-methodを出力します。 @Testの値は値を渡さないため、デフォルト値は出力です。@TestMethodは、注入された文字列を出力します。
@test()public class annotationtest {@testmethod( "tomcat-method")public void test(){} public static void main(string [] args){test t = annotationtest.class.getannotation(test.class); system.out.println(t.value()); testmethod tm = null; try {tm = annotationtest.class.getDeclaredMethod( "test"、null).getAnnotation(testmethod.class); } catch(Exception e){e.printstacktrace(); } system.out.println(tm.value()); }読んでくれてありがとう、私はそれがあなたを助けることができることを願っています。このサイトへのご支援ありがとうございます!