注解的使用

注解也成为元数据,为我们在代码中添加信息提供了一种形式化的方法,使我们可以很方便地使用这些数据.
注解可以提供用来完整地描述程序所需的信息,而这些信息是无法用java表达的,因此,注解使得我们能够以将由编译器来测试和验证的格式,存储有关程序的额外信息。注解可以用来成描述性文件,使用注解我们可以将这些元数据保存在java源码中。
JavaSE5中内置了三种注解,
@Override,表示当前的方法定义将覆盖超类中的方法,拼写错误或者方法签名簿符合覆盖原则,会报错。
@Deprecated,如果程序员使用了注解为它的元素,那么编译器会发出警告信息。
@SuppressWarnings,关闭不当的编译器警告信息。
下面通过一个例子来说明注解的使用,

代码如下:
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

public class Ann {
	@Documented
	@Target({ElementType.TYPE,ElementType.METHOD})
	@Retention(RetentionPolicy.RUNTIME)
	public @interface Yts {
	    public enum YtsType{util,entity,service,model};
	    public YtsType classType() default YtsType.util;
	}

	@Documented
	@Retention(RetentionPolicy.RUNTIME)
	@Target(ElementType.METHOD)
	@Inherited
	public @interface HelloWorld {
		public String name() default "";
	}
}
在这里我们是自定了两个注解,分别为Yts,HelloWorld,下面介绍一下里面的元素
元注解是指注解的注解。包括  @Retention @Target @Document @Inherited四种。
1.@Retention: 定义注解的保留策略
@Retention(RetentionPolicy.SOURCE)   //注解仅存在于源码中,在class字节码文件中不包含
@Retention(RetentionPolicy.CLASS)     // 默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得,
@Retention(RetentionPolicy.RUNTIME)  // 注解会在class字节码文件中存在,在运行时可以通过反射获取到
我们这里用的就是RUNTIME,在程序运行时要用到,
2. @Target(ElementType.TYPE)   //接口、类、枚举、注解
@Target(ElementType.FIELD) //字段、枚举的常量
@Target(ElementType.METHOD) //方法
@Target(ElementType.PARAMETER) //方法参数
@Target(ElementType.CONSTRUCTOR)  //构造函数
@Target(ElementType.LOCAL_VARIABLE)//局部变量
@Target(ElementType.ANNOTATION_TYPE)//注解
@Target(ElementType.PACKAGE) ///包   
 由以上的源码可以知道,他的elementType 可以有多个,一个注解可以为类的,方法的,字段的等等
我们这里的程序第一个注解就是用到了多个elementtype,一个是TYPE,一个是METHOD,说明这个注解对类和方法都是有效的,第二个注解只用到了Method,说明这个注解仅对于方法有效,
3. @Document:说明该注解将被包含在javadoc中
4. @Inherited:说明子类可以继承父类中的该注解
这里说一下,编译器对元素的默认值是有些过分挑剔,首先元素不能有不确定的值,也就是说,元素要么具有默认值,要么在使用注解时提供元素的值,
其次,对于非基本类型的元素,无论是在源代码中声明时,或是在注解接口中定义默认值时,都不能以null作为其值,这个约束使得处理器很难表现一个原素的存在或缺失的状态,因为在所有的注解的声明中,所有的元素都存在,并且都具有相应的值,为了绕开这个约束,我们只能定义一些特殊的值,例如空字符串或负数,以此表示某个元素不存在:
比如下面这个例子:
public class Dana {

	@Target(ElementType.METHOD)
	@Retention(RetentionPolicy.RUNTIME)
	public @interface simulatingNull {
		public int id() default -1;
		public String description() default "";
	}
}


言归正传,下面我们写一个测试类测试一下我们所写的注解,代码如下:
import java.lang.reflect.InvocationTargetException;

import com.ann.Ann.HelloWorld;
import com.ann.Ann.Yts;
import com.ann.Ann.Yts.YtsType;

@Yts(classType = YtsType.util)
public class SayHell {

	@HelloWorld(name = " 小明 ")
	public void sayHello(String name) {
		if (name == null || name.equals("")) {
			System.out.println("hello world!");
		} else {
			System.out.println(name + "say hello world!");
		}
	}

在这里我们可以看到,Yts既是一个类注解,也是一个方法注解,所以它可以写在类的前面,如果这个注解没有定义类这个范围,那么这么写会出错,在这个类中有一个sayHello方法,这里我们用到了HelloWorld方法注解,并为其赋值为“小明”,这个方法是等待调用的,好了,既然用到注解,就需要涉及到注解的解析,不然怎么用呢,下面是解析的代码:

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.ann.Ann.HelloWorld;
import com.ann.Ann.Yts;
import com.ann.Ann.Yts.YtsType;

public class ParseAnnotation {
	 
	public void parseMethod(Class clazz) throws IllegalArgumentException,
			IllegalAccessException, InvocationTargetException,
			SecurityException, NoSuchMethodException, InstantiationException {
		@SuppressWarnings("unchecked")
		Object obj = clazz.getConstructor(new Class[] {}).newInstance(
				new Object[] {});
		for (Method method : clazz.getDeclaredMethods()) {
			HelloWorld say = method.getAnnotation(HelloWorld.class);
			String name = "";
			if (say != null) {
				System.out.println("有值"+method.getAnnotation(HelloWorld.class));
				name = say.name();
				method.invoke(obj, name);
			}
			Yts yts = (Yts) method.getAnnotation(Yts.class);
			if (yts != null) {
				if (YtsType.util.equals(yts.classType())) {
					System.out.println("this is a util method");
				} else {
					System.out.println("this is a other method");
				}
			}
		}
	}

	@SuppressWarnings("unchecked")
	public void parseType(Class clazz) throws IllegalArgumentException,
			IllegalAccessException, InvocationTargetException {
		Yts yts = (Yts) clazz.getAnnotation(Yts.class);
		if (yts != null) {
			System.out.println(clazz.getAnnotation(Yts.class));
			if (YtsType.util.equals(yts.classType())) {
				System.out.println("this is a util class");
			} else {
				System.out.println("this is a other class");
			}
		}
	}
}


第一个方法是方法注解解析,第二个方法是类注解解析,这涉及到很多方法的使用,注释暂时先不写了,以后有时间再详细写,注解解析也写好了,那我们就在刚才写的SayHell类里测试,把下面这段代码加到那个类中,就是一个主函数调用:public static void main(String[] args) throws IllegalArgumentException,
			IllegalAccessException, InvocationTargetException,
			SecurityException, NoSuchMethodException, InstantiationException {
		ParseAnnotation parse = new ParseAnnotation();
		parse.parseMethod(SayHell.class);
		parse.parseType(SayHell.class);
	}
}
大家注意到没有,其实这两部分是可以直接合为一体的,因为本来就是一个类,为了好说明,我把它们拆开了,好了,运行一下,可以得到下面这种效果:
 
说明我们的自定义注解起效了。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
@Import注解是Spring框架中的一个注解,它用于将其他类或配置导入到当前类中。@Import可以单独使用,也可以和其他注解一起使用,例如@Configuration注解ImportSelector接口和ImportBeanDefinitionRegistrar接口。 当@Import注解单独使用时,它可以直接将其他普通的类导入到当前类中,以便在当前类中可以使用被导入的类。 当@Import注解结合@Configuration注解ImportSelector接口和ImportBeanDefinitionRegistrar接口使用时,在Spring Boot中是最常见的用法之一。举个例子,如果我们在一个类上使用@EnableAutoConfiguration注解,那么在该注解的源码中会使用@Import注解来导入AutoConfigurationImportSelector类。这样,通过@EnableAutoConfiguration注解,我们可以自动配置应用程序的一些默认设置。 总结来说,@Import注解是用来将其他类或配置导入到当前类中的注解,可以单独使用,也可以和其他注解一起使用,常见的用法是结合@Configuration注解ImportSelector接口和ImportBeanDefinitionRegistrar接口在Spring Boot中实现自动配置。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [@Import注解的四种使用方式](https://blog.csdn.net/bluemysky/article/details/128827769)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [@Import注解使用](https://blog.csdn.net/m0_55806905/article/details/127967036)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值