简单了java中注解的使用

相信很多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);
	}
}

通过反射获取一个处理好的对象,这个对象当中的所有使用了注解的地方就已经可以发挥他的作用了

猜你喜欢

转载自blog.csdn.net/weixin_43999566/article/details/89550884