创建声明和启动对象的自定义注释

Create Custom annotation which declares and initiates a Object

我想创建一个注解,它将是 Target TYPE 并声明一个自定义 class.

的对象
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Test {
}

class Student{

}

执行

@Test
class example{
    //Want this annotation to declare something like this
    Student s = new Student();
}

注释处理器规范 AFAIK 通常不支持此功能。带注释的 class 不得操纵其自身的 AST

Lombok (which provides the mentioned @Slf4j annotation) 似乎发现了一些不受支持的钩子,这实际上使它成为一个 hack。

如果您仍想做类似的事情,我建议您查看 Lombok source code

更新:

我刚找到一个 Baeldung tutorial,它解释了如何实现自定义 Lombok 注释(不过我还没有读过)。因此,如果您愿意,也许您可​​以在 Lombok 之上构建一些东西。

您可以创建扩展 类 并用 @Test 注释的 CGLIB 代理,您可以将 属性 添加到代理中。但我认为这不会起到任何作用。这是您用于初学者的示例代码。

首先获取带有 Test

注释的 类 的列表
    Reflections reflections = new Reflections ("com.demo");
    Set<Class<?>> testClasses = reflections.getTypesAnnotatedWith(Test.class);

然后使用 CGLIB 创建这些 类 的代理,并将学生 属性 添加到其中。

for (Class<?> test : testClasses) {
    BeanGenerator beanGenerator = new BeanGenerator ();
    beanGenerator.setSuperclass (test);
    beanGenerator.addProperty("student", Student.class);
    Object myBean = (test) beanGenerator.create();  
    Method setter = myBean.getClass().getMethod("setStudent", Student.class);
    setter.invoke(myBean, new Student()); 
}

Maven 依赖项:

<dependency>
    <groupId>cglib</groupId>
    <artifactId>cglib</artifactId>
    <version>3.2.4</version>
</dependency>

<dependency>
    <groupId>org.reflections</groupId>
    <artifactId>reflections</artifactId>
    <version>0.9.11</version>
</dependency>