本練習有三個目標:
1.如何定義注釋類型
2.如何使用注釋類型
3.如何讓注釋影響程序運行
一.如何定義注釋類型
package org.test.spring.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* <p>
* 定義一個Person類專用的注釋
* </p>
* 元注釋Retention用于指定此注釋類型的注釋要保留多久, 元注釋Target用于指定此注釋類型的注釋適用的程序元素的種類,
*
* @author Huy Vanpon
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Annot4Person
{
String name() default "惠萬鵬";
int age() default 25;
String gender() default "男";
}
二.2.如何使用注釋類型
package org.test.spring.annotation;
/**
* <p>
* 本類用于定義人類,包含一個自我介紹的方法
* </p>
*
* @author Huy Vanpon
*/
public class Person
{
@Annot4Person(name = "何潔", gender = "女", age = 16)
public void introductionMyself(String name, String gender, int age)
{
StringBuffer sb = new StringBuffer();
sb.append("嗨,大家好,我叫");
sb.append(name);
sb.append(",今年");
sb.append(age);
sb.append("歲,是一個充滿陽光的");
sb.append(gender);
sb.append("孩.");
System.out.println(sb.toString());
}
}
三.如何讓注釋影響程序運行
package org.test.spring.annotation;
import java.lang.reflect.Method;
/**
* <p>
* 本用利JAVA的反射機制,讓注釋影響程序的運行
* </p>
*
* @author Huy Vanpon
*/
public class AnnotDisturber
{
public void testAnnot4Person()
{
Class<Person> clazz = Person.class;
try
{
//通過方法名和入參確定方法
Method method = clazz.getDeclaredMethod("introductionMyself",
String.class, String.class, int.class);
if (method == null)
{
return;
}
//從方法取得注釋
Annot4Person annotation = method.getAnnotation(Annot4Person.class);
if (annotation == null)
{
return;
}
//調用這個方法
method.invoke(new Person(), annotation.name(), annotation.gender(),
annotation.age());
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
AnnotDisturber tt = new AnnotDisturber();
tt.testAnnot4Person();
}
}