ByteBuddy 支持为动态类和方法添加自定义注解,需注解具有 @Retention(RUNTIME),通过 annotateType() 和 annotateMethod() 方法配合 AnnotationDescription.Builder 构建注解描述;推荐使用 Builder 避免类加载依赖,并可通过反射验证注解是否生效。

ByteBuddy 可以在动态生成类和方法时添加自定义注解,核心是通过 annotateType()、annotateMethod() 等 API 将注解实例(或注解描述器)附加到目标结构上。关键在于:注解必须是运行时可见的(@Retention(RetentionPolicy.RUNTIME)),且 ByteBuddy 支持直接传入注解对象或使用 AnnotationDescription.Builder 构建。
给动态类添加自定义注解
使用 DynamicType.Builder#annotateType() 方法,传入一个实际的注解实例或 AnnotationDescription:
- 若注解类无参数或只有默认值,可直接 new 实例(需确保该注解类在当前 classloader 中可访问)
- 更推荐用
AnnotationDescription.Builder.ofType()构建,支持设置成员值,且不依赖注解类加载
示例:
class MyAnnotation {
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Logged {
String value() default "default";
}
}
// 动态生成类并加注解
new ByteBuddy()
.subclass(Object.class)
.annotateType(AnnotationDescription.Builder.ofType(MyAnnotation.Logged.class)
.define("value", "generated")
.build())
.name("example.GeneratedClass")
.make()
.load(getClass().getClassLoader());
给动态方法添加自定义注解
在定义方法时,用 defineMethod().annotateMethod();或对已有方法调用 method(...).annotateMethod():
-
annotateMethod()接收AnnotationDescription,构建方式与类注解一致 - 支持重复注解(@Repeatable),只需多次调用
annotateMethod()
示例:
.defineMethod("doWork", void.class, Modifier.PUBLIC)
.annotateMethod(AnnotationDescription.Builder.ofType(MyAnnotation.Logged.class)
.define("value", "in-method")
.build())
.intercept(FixedValue.value(null))
使用注解描述器避免类加载依赖
当注解类可能未被加载(如插件场景),应避免直接 new 注解实例。改用 AnnotationDescription 描述其类型与属性:
- 用
TypeDescription.ForLoadedType或字符串类名指定注解类型 - 成员值支持基本类型、String、Class、枚举、其他注解,以及它们的数组
- 数组值用
Arrays.asList(...)或new Object[]{...}传入
示例(不依赖注解类加载):
AnnotationDescription annotation = AnnotationDescription.Builder
.ofType(new TypeDescription.ForLoadedType(MyAnnotation.Logged.class))
.define("value", "safe-build")
.build();
验证注解是否生效
生成类后,可通过反射检查注解是否存在:
- 类注解:
generatedClass.getAnnotation(MyAnnotation.Logged.class) - 方法注解:
generatedClass.getDeclaredMethod("doWork").getAnnotation(MyAnnotation.Logged.class) - 注意:需确保注解有
@Retention(RUNTIME),否则反射不可见
不复杂但容易忽略。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











