public SimpleData() {}
@FormLabel(label="First Name")
public String getFirstname() { return firstname; }
public void
setFirstname(String firstname) {this.firstname = firstname;}
@FormLabel(label="Last Name",width=80)
public String getLastname() { return lastname; }
public void setLastname(String lastname) {
this.lastname = lastname;
}
@FormLabel(label="Postal code",width=10)
public String getPostcode() { return postcode; }
public void setPostcode(String postcode) {
this.postcode = postcode;
}
}
当然,如果我们不查找批注,那么它们对代码的执行就不会造成任何不同。我们所需要的是在运行期间使用批注的方式;我们通过Reflection API来达到这一目的。现在就让我们创建一个简单的processForm方法,它能够在任何对象里查找批注。
public void processForm(Object o) {
for(Method m:o.getClass().getMethods()) {
我们将在传递给方法的对象的类里定义所有的方法。现在,我们需要检查每个方法,看看它们是否有FormLabel批注,以及是否返回一个String(为了简单地说明问题,我们给所有的结果多返回一些代码):
if(m.isAnnotationPresent(FormLabel.class) &&
m.getReturnType()==String.class) {
现在我们可以通过使用Method的getAnnotation()方法来提取FormLabel批注:
FormLabel formLabel=
m.getAnnotation(FormLabel.class);
现在我们执行方法来取得其字符串值,并通过在批注接口里定义的方法访问批注属性。下面我们就把它们打印出来:
try {
String value=(String)m.invoke(o);
String label=formLabel.label();
int width=formLabel.width();
System.out.printf("%s[%d]:%s ",label,width,value);
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
}
catch (IllegalAccessException ex) {
ex.printStackTrace();}
catch (InvocationTargetException ex) {
ex.printStackTrace();
}
}
}
}
现在我们可以创建含有@FormLabel批注的新类,并把它们传递给processForm方法。这是在运行期间访问你自己的批注的基础。
现在这个时候,我们回头看看Java 5里面其他关于批注的内容。首先是编译器指令――@Deprecated和@SuppressWarnings。@Deprecated是把方法标示为被否定的增强方法;不推荐把它用在新代码里,以防止以后删除。用@Deprecated可以生成一个来自编译器的相关警告。
@SuppressWarnings会阻止编译器在封闭代码元素里警告你,所以你可以在类定义的开始或者对特定的方法使用@SuppressWarnings。它可以带参数,用来指定需要取消的错误的类型,例如:
@SuppressWarnings("unchecked")
public List getList() {
List l=