Java 注解(Annotation)是一种元数据机制,用来给代码(类、方法、字段、参数等)添加说明信息,可以被编译器、框架或运行时读取并使用。
下面从 是什么 → 怎么用 → 怎么自定义 → 常见场景 逐步说明。
@Override
public String toString() {
return "hello";
}
常见内置注解:
@Override:表示方法重写@Deprecated:表示已过时@SuppressWarnings("unchecked"):抑制警告@MyAnnotation
public class User {
@MyAnnotation
private String name;
@MyAnnotation
public void hello(@MyAnnotation String msg) {
}
}
可用于:
public @interface MyAnnotation {
}
使用:
@MyAnnotation
public void test() {}
public @interface MyAnnotation {
String value();
int age() default 18;
}
使用:
@MyAnnotation(value = "tom", age = 20)
public void test() {}
如果只有一个 value():
@MyAnnotation("tom")
@Target(ElementType.METHOD)
常见取值:
TYPE(类)METHODFIELDPARAMETER@Retention(RetentionPolicy.RUNTIME)
取值:
SOURCE:只存在于源码CLASS:编译期RUNTIME:运行时(最常用)@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
String value() default "";
}
Method method = obj.getClass().getMethod("test");
if (method.isAnnotationPresent(Log.class)) {
Log log = method.getAnnotation(Log.class);
System.out.println(log.value());
}
✅ 只有 @Retention(RUNTIME) 的注解才能被反射读取
@RestController
@RequestMapping("/user")
public class UserController {
@GetMapping("/{id}")
public User get(@PathVariable Long id) {
return null;
}
}
@NotNull
private String name;
@Log("用户登录")
public void login() {}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestCase {
String name();
}
public class Demo {
@TestCase(name = "测试1")
public void m1() {}
public static void main(String[] args) throws Exception {
for (Method m : Demo.class.getMethods()) {
if (m.isAnnotationPresent(TestCase.class)) {
TestCase t = m.getAnnotation(TestCase.class);
System.out.println(t.name());
}
}
}
}
Java 注解 = 给代码打标签 + 编译器/框架/反射读取并使用
如果你愿意,我也可以:
你想看哪一种?
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。