6

アノテーションはJavaでどのように機能しますか?そして、どうすれば次のようなカスタム注釈を作成できますか?

@Entity(keyspace=':')
class Student
{
  @Id
  @Attribute(value="uid")
  Long Id;
  @Attribute(value="fname")
  String firstname;
  @Attribute(value="sname")
  String surname;

  // Getters and setters
}

基本的に、私が必要としているのは、このPOJOが永続化されるときに次のようにシリアル化されることです。

dao.persist(new Student(0, "john", "smith")); 
dao.persist(new Student(1, "katy", "perry"));

そのため、実際に生成/永続化されたオブジェクトは次のMap<String,String>ようになります。

uid:0:fname -> john
uid:0:sname -> smith
uid:1:fname -> katy
uid:1:sname -> perry

これを実装する方法はありますか?

4

1 に答える 1

3

カスタムアノテーションを作成する場合は、APIExampleHereを使用Reflectionし てそれらを処理する必要がありますアノテーションの宣言方法を参照できます。 Javaでのアノテーション宣言の例は次のようになります。

import java.lang.annotation.*;

/**
 * Indicates that the annotated method is a test method.
 * This annotation should be used only on parameterless static methods.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Test { }

RetentionとしてTarget知られていmeta-annotationsます。

RetentionPolicy.RUNTIME実行時に注釈を保持し、実行時にアクセスできることを示します。

ElementType.METHODクラスレベル、メンバー変数レベルなどのアノテーションを構成できるのと同様に、メソッドでのみアノテーションを宣言できることを示します。

各Reflectionクラスには、宣言されたアノテーションを取得するためのメソッドがあります。

public <T extends Annotation> T getAnnotation(Class<T> annotationClass)
Returns this element's annotation for the specified type if such an annotation is present, else null.

public Annotation[] getDeclaredAnnotations()
Returns all annotations that are directly present on this element. Unlike the other methods in this interface, this method ignores inherited annotations. (Returns an array of length zero if no annotations are directly present on this element.) The caller of this method is free to modify the returned array; it will have no effect on the arrays returned to other callers. 

これらのメソッドは、、、クラスに存在しFieldます。MethodClass

例:実行時に指定されたクラスに存在するアノテーションを取得するには

 Annotation[] annos = ob.getClass().getAnnotations();
于 2012-09-04T05:49:58.367 に答える