java - 创建自定义注释

标签 java annotations

注释如何与 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

有什么想法可以实现吗?

最佳答案

如果您创建自定义注释,则必须使用 Reflection API Example Here处理它们。 可以引用How to declare annotation. 以下是 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 { }

RetentionTarget 被称为 meta-annotations

RetentionPolicy.RUNTIME表示要在运行时保留注解,运行时可以访问。

ElementType.METHOD 表示您只能在方法上声明注释,类似地,您可以为类级别、成员变量级别等配置注释。

每个反射类都有方法来获取已声明的注释。

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. 

您会发现这些方法适用于 FieldMethodClass 类。

例如,在运行时检索指定类上的注解

 Annotation[] annos = ob.getClass().getAnnotations();

关于java - 创建自定义注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12257431/

相关文章:

java - 我应该如何正确使用@Value?

java - Kotlin 数据类型是基于原始或非原始 Java 数据类型构建的吗?

java - hibernate 错误: Illegal Attempt to deference collection

java - Java Annotation 的默认属性

ios - 如何使整个调用可点击?

ios - 注释在动画结束前不可点击

python - 如何在不注释类型的情况下添加数据类字段?

Java - 非匿名比较器模拟从集合中选择元素

java - 默认参数值在 iReport 中有效,但在 JasperServer 中无效

java - 创建 Java 模型类