Java注解与反射系列——注解与反射实例
实例
用于获取所有带有注解的方法的方法名并记录日到txt中
CheckMethod注解
package example.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CheckMethod {
String value()default "";
}
Stu类
类中有三个自定义的方法:runAway,eat,cry,其中前两个家里CheckMethod注解
package example.reflect.entity;
import example.annotation.AnnoField;
import example.annotation.CheckMethod;
import example.annotation.MyAnno;
@MyAnno(value = "stu_class")
public class Stu {
@AnnoField(col = "NAME",type = "String")
private String name;
@AnnoField(col = "AGE",type = "Number")
private int age;
private String id;
public Stu(String name, int age, String id) {
this.name = name;
this.age = age;
this.id = id;
}
public Stu() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@CheckMethod()
public void runAway(){
System.out.println("run away ...");
}
@CheckMethod()
public void eat(String food){
System.out.println("eat some "+ food);
}
public void cry(){
System.out.println("cry loud ...");
}
@Override
public String toString() {
return "Stu{" +
"name='" + name + '\'' +
", age=" + age +
", id='" + id + '\'' +
'}';
}
}
测试
package example.reflect;
import example.annotation.CheckMethod;
import example.reflect.entity.Stu;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Method;
/**
* 判断注解测试框架,记录到文件txt中
*/
public class DoDemo {
public static void main(String[] args) throws IOException {
//记录第几个方法
int line = 0;
//文件
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("D:\\haveAnno.txt"));
//通过反射获取类
Class<Stu> stuClass = Stu.class;
//获取所有的方法
Method[] methods = stuClass.getMethods();
for (Method method : methods) {
line++;
//判断是否有CheckMethod注解,有则打印名字
if (method.isAnnotationPresent(CheckMethod.class)) {
System.out.println(method.getName());
//记录到文件
bufferedWriter.write("have Anno: Num :" + line + "CheckMethod!: " + method.getName());
bufferedWriter.newLine();
}
}
bufferedWriter.flush();
bufferedWriter.close();
}
}