最近一段时间在整理基础的东西, 看到@interface 这个就去具体的查看了下注解的使用, 以下是本人自己整理的代码, 话不多说, 上代码:
自定义注解类
package com.huntkey.rx.sceo.utils;
import java.lang.annotation.*;
/**
* @description: 自定义注解实现特定功能
* 描述:
* @interface: 表示继承了java.lang.annotation.Annotation 是个注解, 不是接口, 用来修饰
* 类,方法,参数,本地变量,包、元数据等
*
* 注意: 方法名对应参数名,返回值类型对应参数类型
*
* 使用: public @interface 自定义注解名 { 自定义注解体 }
* 自定义注解体支持以下元素类型: (包装类型不支持)
* 1. 八大基本数据类型(byte,boolean,char,short, int, long, float, double)
* 2. String 类型
* 3. enum 类型
* 4. Class 类型
* 5. Annotation类型
* 6. 以上所有类型的数据
*
* @author: wangml
* @date: 2021/7/19 17:14
*/
@Target(value={ElementType.TYPE, ElementType.METHOD}) // 定义注解的使用位置, 没有该注解, 默认可以使用在任何地方
@Retention(RetentionPolicy.RUNTIME) // 定义保留策略{SOURCE: 源码级别保留, 编译后丢弃; CLASS: 编译级别保留, class文件中保留, 允许时丢弃, 默认值; RUNTIME: 运行时保留, 编译后的class文件中存在,在jvm运行时保留,可以被反射调用}
@Documented // 修饰的注解,可以被例如javadoc此类的工具文档化
@Inherited // 表明此注解@Wml可以被子类继承
public @interface Wml {
/**
* 注解方法(不是属性)
*
* @return
*/
boolean isUser() default false;
String name() default "";
String passWord() default "";
}
使用注解类
package com.huntkey.rx.sceo.utils;
import lombok.Data;
/**
* @description: 自定义注解的使用
* @author: wangml
* @date: 2021/7/20 09:43
*/
@Wml(isUser=true, name="mahao", passWord = "qwer")
@Data
public class SelfAnnotation {
}
测试@Wml注解使用
package com.huntkey.rx.sceo.mytest;
import com.huntkey.rx.sceo.utils.SelfAnnotation;
import com.huntkey.rx.sceo.utils.Wml;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @description:
* @author: wangml
* @date: 2021/7/20 09:47
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class AnnotationTest {
@Test
public void testAnnotationUse() throws ClassNotFoundException {
// 通过反射获取类上的注解(反射可以获取类上的所有信息, 包括属性注解, 类注解, 类属性, 属性返回数据等等)
// 全限定名获取
Class class1 = Class.forName("com.huntkey.rx.sceo.utils.SelfAnnotation");
// java类型获取
Class class2 = SelfAnnotation.class;
// 实例化对象获取
SelfAnnotation selfAnnotation = new SelfAnnotation();
Class class3 = selfAnnotation.getClass();
Wml wml = (Wml) class1.getAnnotation(Wml.class);
if(wml.isUser()) {
System.out.println("SelfAnnotation类上的isUser为真");
}
if ("mahao".equals(wml.name()) && "qwer".equals(wml.passWord())) {
System.out.println("SelfAnnotation类上用户名和密码正确");
}
}
}
控制台输出
2021-07-20 10:44:12.728 INFO 9532 --- [ main] c.huntkey.rx.sceo.mytest.AnnotationTest : Started AnnotationTest in 3.733 seconds (JVM running for 5.296)
SelfAnnotation类上的isUser为真
SelfAnnotation类上用户名和密码正确
2021-07-20 10:44:13.011 INFO 9532 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
总结
- 可以用来 根据自己功能需求定制化功能注解, 比如要实现 spring boot 的相关功能使用了@SpringBootApplication, 在@SpringBootApplication 中集成了@SpringBootConfiguration 和@EnableAutoConfiguration等其他有自己特定功能的注解.
- 可以实现切面功能, 在某些类, 方法引入了该注解, 在自定义注解中执行某种操作, 当引入了该注解时所有类和方法自动实现了自定义注解中的功能(自己的理解)