package com.annotation;
import java.lang.annotation.*;
// 定义一个自定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.FIELD,ElementType.METHOD,ElementType.CONSTRUCTOR})
@Documented
@Inherited
@interface MyAnnotation {
String value() default "";
}
// 使用自定义注解
@MyAnnotation("Class Annotation")
public class DemoClass {
@MyAnnotation("Field Annotation")
private String field;
@MyAnnotation("Constructor Annotation")
public DemoClass() {
// 构造函数注解
}
@MyAnnotation("Method Annotation")
public void demoMethod() {
// 方法注解
}
public static void main(String[] args) {
DemoClass obj = new DemoClass();
Class<? extends DemoClass> clz = obj.getClass();
// 获取类上的注解
MyAnnotation classAnnotation = clz.getAnnotation(MyAnnotation.class);
System.out.println("Class Annotation: " + classAnnotation.value());
// 获取字段上的注解
try {
java.lang.reflect.Field field = clz.getDeclaredField("field");
MyAnnotation fieldAnnotation = field.getAnnotation(MyAnnotation.class);
System.out.println("Field Annotation: " + fieldAnnotation.value());
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
// 获取构造函数上的注解
try {
java.lang.reflect.Constructor<?> constructor = clz.getDeclaredConstructor();
MyAnnotation constructorAnnotation = constructor.getAnnotation(MyAnnotation.class);
System.out.println("Constructor Annotation: " + constructorAnnotation.value());
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
// 获取方法上的注解
try {
java.lang.reflect.Method method = clz.getDeclaredMethod("demoMethod");
MyAnnotation methodAnnotation = method.getAnnotation(MyAnnotation.class);
System.out.println("Method Annotation: " + methodAnnotation.value());
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
没有合适的资源?快使用搜索试试~ 我知道了~
温馨提示
内容概要: Java注解是一种用于提供元数据的特殊注释形式,可以应用于类、方法、字段和其他程序元素。这些元数据描述了程序结构、行为或属性的信息。Java注解以@符号开始,并包含注解名称和相关属性。Java提供了许多内置注解,同时也支持自定义注解。 适用人群: Java注解适用于所有使用Java编程语言的开发者。不论是开发框架、库,还是进行特定行为的配置和处理,都可以从使用注解中获益。 使用场景: 以下是一些适合使用Java注解的常见场景: 在源代码中标记和解析特定元素,如类、方法、字段等。 通过注解来配置和参数化框架,指示特定行为或属性的设置。 自动生成文档或测试报告的过程中,使用注解提取重要信息或生成相关文档。 运行时处理的过程中,通过注解获取元数据并执行相应的操作。 目标: Java注解的目标是为了提供一种声明性的方式来描述和配置程序行为、结构和属性的元数据。它可以帮助开发者更好地理解和维护代码,并提供灵活性和可读性。注解为开发者提供了与其他工具和框架集成的机制,使他们能够更高效地构建、扩展和定制应用程序。
资源推荐
资源详情
资源评论
收起资源包目录
src.zip (2个子文件)
src
com
annotation
DemoClass.java 2KB
AnnotationDemo.java 2KB
共 2 条
- 1
资源评论
小山code
- 粉丝: 1w+
- 资源: 20
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功