概述:
注解开发对于java的web开发来说用的很少但是了解注解开发的原理有助我们更好的理解在框架中是如何实现注解与方法的执行
示例
定义注解
package com.action.Annotion;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAno {
String path() default "make have atry";
String method() default "GET";
}
建立测试类
package com.action.Test;
import com.action.Annotion.TestAno;
public class HellowWord {
@TestAno(path = "hellow")
public void sayHellow(){
System.out.println("hellow word ");
}
@TestAno(path = "bebetter")
public void sayNo(String num){
System.out.printf("i am number"+num);
}
}
实现方法
package com.action.Test;
import com.action.Annotion.TestAno;
import com.action.controller.MailController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class FileTest {
public void say(){
System.out.println("hellow");
}
public static void main(String[] args) {
HellowWord hellowWord=new HellowWord();
通过字节吗获取方法集合
Method[] methods =new HellowWord().getClass().getDeclaredMethods();
遍历方法集合
for (Method method:methods){
Annotation object= method.getAnnotation(TestAno.class);
将注解转为String格式便于对注解进行判断
String annotion=object.toString();
try {
执行方法第一个object为所要执行的类 ,后面是参数 则代表无参数
method.invoke(hellowWord);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}