创建自定义注释 [英] Creating custom annotations

查看:42
本文介绍了创建自定义注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注解如何与 Java 一起工作?我如何创建这样的自定义注释:

How does annotation work with Java? And how can I create custom annotations like this:

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

  // Getters and setters
}

基本上,我需要的是这个 POJO 在持久化时像这样序列化:

Basically, what I need to have is this POJO be serialized like this when persisted:

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

这样,实际生成/持久化的对象是一个Map,如下所示:

Such that, the actual generated/persisted object is a Map<String,String> like this:

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

任何想法如何实施?

推荐答案

如果您创建自定义注释,则必须使用 Reflection API 示例在这里 来处理它们.您可以参考如何声明注解.下面是 java 中的注解声明示例.

If you create custom annotations you will have to use Reflection API Example Here to process them. You can refere How to declare annotation. Here is how example annotation declaration in java looks like.

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 表示希望在运行时保留注解,并且可以在运行时访问.

RetentionPolicy.RUNTIME indicates that you want to retain the annotation at runtime and you can access it at runtime.

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

ElementType.METHOD indicates that you can declare annotation only on methods similarly you can configure your annotation for class level, member variable level etc.

每个反射类都有方法来获取声明的注解.

Each Reflection class has methods to get annotations which are declared.

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 类.

You will find these methods present for Field, Method,Class classes.

例如在运行时检索指定类上存在的注释

e.g.To retrieve annotations present on specified class at run time

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

这篇关于创建自定义注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆