java 如何用注解
在Java中,注解(Annotation)是一种元数据形式,用于为代码提供附加信息。以下是使用注解的常见方法和场景:
定义自定义注解
通过@interface关键字定义注解,可以指定元注解(如@Target、@Retention)来控制注解的行为:
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CustomAnnotation {
String value() default "default";
int priority() default 1;
}
使用内置注解
Java提供了一些内置注解,例如:
@Override:标记方法重写父类或接口的方法。@Deprecated:标记方法或类已过时。@SuppressWarnings:抑制编译器警告。
@Override
public String toString() {
return "Overridden method";
}
处理运行时注解
通过反射机制读取运行时注解信息:
Method method = obj.getClass().getMethod("annotatedMethod");
if (method.isAnnotationPresent(CustomAnnotation.class)) {
CustomAnnotation annotation = method.getAnnotation(CustomAnnotation.class);
System.out.println(annotation.value());
}
注解处理器
编译时处理注解需继承AbstractProcessor并注册:
@SupportedAnnotationTypes("com.example.CustomAnnotation")
public class CustomProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
for (Element element : roundEnv.getElementsAnnotatedWith(CustomAnnotation.class)) {
// 处理逻辑
}
return true;
}
}
框架中的注解应用
主流框架广泛使用注解简化开发:

- Spring的
@Controller、@Autowired。 - JUnit的
@Test。 - JPA的
@Entity、@Column。
@RestController
@RequestMapping("/api")
public class MyController {
@GetMapping("/hello")
public String hello() {
return "Hello World";
}
}






