“现在让我们创建并使用一些注释。”

“比如,假设我们正在编写一个游戏引擎。我们的游戏有很多角色,分为三类:精灵、宫廷守卫和反派。”

“随着游戏的开发,可能会添加新角色,这将改变游戏平衡。因此,为每个‘角色类别’分配描述其物理特征的注释会非常方便。”

“这样做可以很容易地模拟不同角色之间的战斗和/或快速计算游戏平衡。”

“我同意。这是个好主意。”

“让我们创建一个@Person注释,它将存储生命、力量和魔法,以及攻击和防御参数。注释如下所示:”

例子
@interface Person
{
 String name() default "";
 int live();
 int strength();
 int magic() default 0;
 int attack() default 0;
 int defense();
}

“而且,举个例子,森林精灵法师的描述是这样的:”

例子
@Person(live = 100, strength = 10, magic = 5, attack = 20, defense = 20)
class Elf
{
 …
}

“下面是主要反派的描述:”

例子
@Person(live = 1000, strength = 150, magic = 250, attack = 99, defense = 99)
class EvilMaster
{
 …
}

“我明白了。它让我想起了一些标记界面。”

“是的。除了,第一,你不必继承任何东西。第二,你可以在注释中存储额外的信息。”

“还有几个用于标记注释的注解,这里是:

“@Retention 注释指示我们的注释在哪里可见:仅在源代码中,甚至在编译之后,甚至在运行时。”

“@Target 注解指明了具体可以使用注解标记的内容:类、字段、方法、方法参数等。”

“如果我们希望我们的注解应用于继承注解类的类,而不仅仅是注解类本身,那么我们需要使用@Inherited 对其进行注解。”

“这就是我们的@Person.annotation的样子。”

例子
@Target(value = ElementType.TYPE)
@Retention(value = RetentionPolicy.RUNTIME)
@interface Person
{
 String name() default "";
 int live();
 int strength();
 int magic() default 0;
 int attack() default 0;
 int defence();
}

“这很有趣,谢谢你,Rishi。”

但是你如何在程序中使用这些注释呢?你如何使用它们?你如何解读他们的价值观?”

“这通常是使用Reflection完成的。”

“以下是我们如何确定哪个角色更强:”

例子
public boolean fight(Class first, Class second)
{
 if (!first.isAnnotationPresent(Person.class))
  throw new RuntimeException("first param is not game person");
 if (!second.isAnnotationPresent(Person.class))
  throw new RuntimeException("second param is not game person");

 Person firstPerson = (Person) first.getAnnotation(Person.class);
 Person secondPerson = (Person) second.getAnnotation(Person.class);

 int firstAttack = firstPerson.attack() * firstPerson.strength() + firstPerson.magic();
 int firstPower = firstPerson.live() * firstPerson.defence() * firstAttack;

 int secondAttack = secondPerson.attack() * secondPerson.strength() + secondPerson.magic();
 int secondPower = secondPerson.live() * secondPerson.defence() * secondAttack;

 return firstPower > secondPower;
}

“这是我们需要的方法:”

方法 描述
isAnnotationPresent(Annotation.class)
检查类是否有指定的注解
getAnnotation(Annotation.class)
如果类具有指定的注释,则返回一个注释对象。
Annotation[] getAnnotations()
返回所有类注释的数组

“太好了,没想到得到注解这么简单。”

“嗯。” 只需调用对象的 getAnnotation 方法,传入所需的注释类型。”

“今天到此为止。”

“谢谢你,Rishi。这是一堂非常有趣的课。现在我不再像害怕水一样害怕注释了。”