自定义注解

package cn.stu;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyController {

	String  controller()  default "";
	
}
package cn.stu;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

 

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyService {

	String service() default "";
	
	
}

package cn.stu;

public class MyActivity {
    
	@MyController(controller="login")
	private String  controller;
	
	@MyService(service="loginService")
	private String  service;

	public String getController() {
		return controller;
	}

	public void setController(String controller) {
		this.controller = controller;
	}

	public String getService() {
		return service;
	}

	public void setService(String service) {
		this.service = service;
	} 
	 
}

package cn.stu;

import java.lang.reflect.Field;

/***
 * 
 *  猜测,Spring在初始化的时候, 有一个扫描的配置, 在这里就获取某一个包下面的所有的类。 然后通过反射就对其中的类进行数据的填充。 
 *  进行初始化扫描下面的类。 (个人猜测)
 *  
 *  
 *  注解形式主要的也就是通过反射机制来进行数据的填充,在代码运行的时候执行。 如此理解Spring的注解的形式就好理解了。所有的注解也就
 *  是一个差不多的普通类而已,只是通过反射来进行初始化和数据的填充。
 * 
 * 
 */
public class Main {

	public static void main(String[] args) {
		 
		String[] str = Main.getFiledInfo(MyActivity.class);
        for (String string : str) {
			System.out.println(string);
		}
	}
	
	
	// 反射解析注解数据
	public  static String[]  getFiledInfo(Class<?> clazz){
		String[] strData = new String[2];
		Field[] fileds = clazz.getDeclaredFields(); // 反射获取所有属性,这里只是定义来属性注解
		
		for (Field field : fileds) {
			  if(field.isAnnotationPresent(MyController.class)){
				    MyController controller = (MyController)field.getAnnotation(MyController.class);
				    String loginController = controller.controller();
				    strData[0] = "登录请求地址->"+loginController;
				  
			  }else if(field.isAnnotationPresent(MyService.class)){
				    MyService service = (MyService)field.getAnnotation(MyService.class);
				    String loginService = service.service();
				    strData[1] = "登录业务处理->"+loginService;
			  }
		}
		return strData;
	}
	
	
	

}


打印如下:

  

登录请求地址->login

登录业务处理->loginService


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值