Skip to content

Repository files navigation

Reflect Annotations

reflect-annotations 是一个轻量级、零运行时开销的 Java 注解库。它旨在通过声明式注解标记类与字段,配合构建期插件(如 Gradle 插件)自动收集元数据,用于动态生成反射配置文件(如 GraalVM reflect-config.json 等)。

特性

  • 零运行时开销:注解保留策略为 SOURCE,不会被编译进字节码,运行时无任何性能损耗。
  • 安全可控的默认值
    • 类级别的反射选项(构造函数、方法)默认开启,减少样板代码。
    • 字段级别的反射默认关闭,遵循最小权限原则,仅通过 @ReflectField 按需开启。
  • 框架无关:不绑定特定的底层运行时或工具链(如 GraalVM),专注于反射意图的表达。

安装

Gradle

将核心包引入到您的项目中(通常作为 compileOnlyimplementation 依赖):

dependencies {
    implementation 'io.github.neallon:reflect-annotations:1.0'
}

快速上手

1. 使用 @Reflectable 标记类

在需要保留反射能力的类或接口上添加 @Reflectable 注解。您可以根据需要调整默认的反射行为:

import io.github.neallon.reflect.annotation.Reflectable;
import io.github.neallon.reflect.annotation.ReflectField;

@Reflectable(
    publicConstructors = true,
    declaredConstructors = true,
    publicMethods = true,
    declaredMethods = true,
    publicFields = false,
    declaredFields = false
)
public class User {
    private Long id;
    
    @ReflectField
    private String username; // 仅允许反射访问该特定字段

    private String password;

    public User() {}

    public User(Long id, String username) {
        this.id = id;
        this.username = username;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}

2. 注解属性说明

@Reflectable (作用于类 / 接口)

属性 类型 默认值 说明
publicConstructors boolean true 是否包含所有公共构造函数
declaredConstructors boolean true 是否包含所有已声明(含私有/保护)构造函数
publicMethods boolean true 是否包含所有公共方法
declaredMethods boolean true 是否包含所有已声明方法
publicFields boolean false 是否包含所有公共字段
declaredFields boolean false 是否包含所有已声明字段

@ReflectField (作用于字段)

属性 类型 默认值 说明
enabled boolean true 是否允许该字段参与反射元数据生成

配套插件开发计划

本核心包需配合配套的编译期构建插件(如 Gradle 插件)使用:

  1. 在编译阶段通过注解处理器(Annotation Processor)或 AST 扫描源码。
  2. 收集带有 @Reflectable@ReflectField 的目标类及成员结构。
  3. 自动在目标路径(例如 META-INF/native-image/)输出对应的反射配置文件。

许可证

MIT License

About

A lightweight, zero-overhead Java annotation library for generating reflection metadata.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages