自定义注解
Java自带的注解的作用是帮助我们减少错误,比如Overwrite就提醒我们必须对该方法进行重写,或继承父类的实现。@Deprecated提示我们这个方法已经被弃用了,有更好的替代者。
自定义注解也有类似的作用,但是更重要的实现是和反射配合使用,是各种java框架的灵魂,主要的作用是实现将我们的写的类根据不同的注解进行分类管理,并且还能将我们写的类和注解的信息进行动态的绑定,让我们实现更加强大的功能,而这些功能是通过框架本身进行管理的,无需我们去操心,我们只要关系注解在框架中的作用就可以了,一个字就是🐂🍺
自定义注解和读取自定义注解的例子
package com.jstar;
import javax.annotation.Resource;
import java.lang.annotation.*;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
* @author Jstar
* @version 1.0
* @date 2021/7/1 11:10 下午
*/
public class ReflectTest {
@MyAnnotation(name = "Tom")
public void test() {
}
@Deprecated
@MyAnnotation(name = "jam")
public void test2() {
}
public static void main(String[] args) throws ClassNotFoundException {
// get Class object
ReflectTest reflectTest = new ReflectTest();
Class<?> aClass = reflectTest.getClass();
// get annotation from object.method
Method[] methods = aClass.getMethods();
HashMap<String, String> MethodAnnotations = new HashMap<>();
for (Method method : methods) {
String annotation = "";
// filter condition of My own annotation
if (method.isAnnotationPresent(MyAnnotation.class)) {
MyAnnotation methodAnnotation = method.getAnnotation(MyAnnotation.class);
annotation = methodAnnotation.name();
MethodAnnotations.put(method.getName(), annotation);
}
}
// Stream out
MethodAnnotations.forEach((s, v) -> System.out.println( "Method name " + s + "annotation name " + v));
// entrySet use test
for (Map.Entry<String, String> stringStringEntry : MethodAnnotations.entrySet()) {
System.out.println(stringStringEntry.getKey() + stringStringEntry.getValue());
}
}
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
// 参数
String name();
}
}
输出