相信很多javaweb開發者都會使用到spring,spring提供了大量的注解,今天我們來寫一套自己的注解,我會寫一個注解可以在屬性上,類上,方法上使用,當注解在類上就輸出一句話,在方法上就嗲用方法,在屬性上就給屬性指派
首先需要使用@interface建立一個自己的注解
package com.zj;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE , ElementType.METHOD , ElementType.FIELD}) //表示此注解可以在屬性,方法,類上使用
@Retention(RetentionPolicy.RUNTIME) //表示注解運作時可見
public @interface RequestMapper {
String value() default "" ;
}
好了注解已經定義好了,但是僅僅定義了注解是沒什麼用的,注解隻是一個辨別,并沒有任何含義,我們需要為它寫一個處理器
package com.test;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import com.zj.RequestMapper;
@RequestMapper("Hello World")
public class Test {
@RequestMapper("wf")
public String name ;
@RequestMapper("哈哈哈")
public void say(String word){
System.out.println(word);
}
//注解處理器,參數是使用了該注解的類的反射
public Object doZj(Class<?> c) throws Exception{
//利用反射産生一個執行個體對象
Object obj = c.newInstance() ;
//首先擷取類上面的注解
RequestMapper reMapper = c.getAnnotation(RequestMapper.class) ;
if(reMapper != null){
//将注解中的值輸出
System.out.println(reMapper.value());
}
//擷取屬性的注解
Field[] fields = c.getDeclaredFields() ;
for (Field f : fields) {
f.setAccessible(true);
reMapper = f.getAnnotation(RequestMapper.class) ;
if(reMapper != null){
//給屬性指派
f.set(obj, reMapper.value());
}
}
//查找方法
Method[] methods = c.getDeclaredMethods() ;
for (Method m : methods) {
m.setAccessible(true);
reMapper = m.getAnnotation(RequestMapper.class) ;
if(reMapper != null){
m.invoke(obj, reMapper.value()) ;
}
}
return obj ;
}
public static void main(String[] args) throws Exception {
Test test = new Test();
test = (Test) test.doZj(Test.class);
System.out.println(test.name);
}
}
通過反射擷取一個處理好的對象,這個對象當中的所有使用了注解的地方就已經可以發揮他的作用了