Background
Reflection makes Java a semi-dynamic language. Hardly do we use reflection in our Java development due, it provides us with an alternative way to create object. Normally, we use new
keyword or clone()
method to create instances. With the help of reflection, we can have the third way.
For annotations, we often see them in frameworks like spring. I believe most of frameworks having annotations are using reflection to get the annotation in our code.
Annotation
An annotation is similar to a class, but it only have attributes. We can use @interface
to declare annotations:
// Self-defined annotations:
// The table name
@Target(value=ElementType.TYPE)
@Retention(value=RetentionPolicy.RUNTIME)
@interface AnnoTable {
// 注解的参数: 参数类型 参数名()
String value();
}
// The field information
@Target(value=ElementType.FIELD)
@Retention(value=RetentionPolicy.RUNTIME)
@interface AnnoField {
String fieldName();
String dataType();
int length();
}
Now let's define a class and use our annotations to describe it:
@AnnoTable("researchers")
class Researcher {
@AnnoField(fieldName = "rid", dataType = "int", length = 11)
private int id;
@AnnoField(fieldName = "age", dataType = "int", length = 11)
private int age;
@AnnoField(fieldName = "name", dataType = "varchar", length = 30)
private String name;
public Researcher() {
}
public Researcher(int id, int age, String name) {
super();
this.id = id;
this.age = age;
this.name = name;
}
// ... getters and setters
}
Get annotation by reflection
public class TestMyAnnotation {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
// 通过反射获得注解
Class c1 = Class.forName("annotation.Researcher");
Annotation[] as = c1.getAnnotations();
for(Annotation a: as) {
System.out.println(a);
}
// 获得注解中的值
AnnoTable annotable = (AnnoTable) c1.getAnnotation(AnnoTable.class);
String value = annotable.value();
System.out.println(value);
// only public fields can be got by getField() method
// private fields should use getDeclaredField()
Field f = (Field) c1.getDeclaredField("id");
AnnoField annoField = (AnnoField) f.getAnnotation(AnnoField.class);
System.out.println(annoField.fieldName());
System.out.println(annoField.dataType());
System.out.println(annoField.length());
}
}
Top comments (0)