有没有办法在 Java 中使用注释来替换访问器?

时间:2023-04-04
本文介绍了有没有办法在 Java 中使用注释来替换访问器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我对 Java 5 注释有点陌生,我很好奇其中任何一个是否可行:

I'm a little new to the Java 5 annotations and I'm curious if either of these are possible:

这个注解会为你生成一个简单的getter和setter.

This annotation would generate a simple getter and setter for you.

@attribute
private String var = "";

@NotNull 注释表示变量不能为空,因此您不必每次都编写样板代码.

The @NotNull annotation indicates that a variable connot be null so you don't have to write that boilerplate code every time.

/*
 * @param s @NotNull
 */
public void setString(String s){
    ...
}

这些都行吗?如果可以的话,它们似乎是我写注释的第一件事.因为当我阅读文档时我看不到太多关于这些的内容,所以我假设这并不是注释的真正含义.任何方向都将不胜感激.

Will either of these work? They seem like the first things I would write annotations for if I could. Since I don't see much about these when I read the docs I'm assuming that it's not really what annotations are about. Any direction here would be appreciated.

推荐答案

注解处理发生在抽象语法树上.这是解析器创建并由编译器操作的结构.

Annotation processing occurs on the abstract syntax tree. This is a structure that the parser creates and the compiler manipulates.

当前的规范(链接来)说注释处理器不能改变抽象语法树.这样做的后果之一是不适合进行代码生成.

The current specification (link to come) says that annotation processors cannot alter the abstract syntax tree. One of the consequences of this is that it is not suitable to do code generation.

如果您喜欢这种功能,请查看 XDoclet.这应该为您提供我认为您正在寻找的代码生成预处理.

If you'd like this sort of functionality, then have a look at XDoclet. This should give you the code generation preprocessing I think you are looking for.

对于您的 @NonNull 示例,JSR-305 是注释集,用于增强软件缺陷检测,包括@NonNull@CheckForNull 以及许多其他人.

For your @NonNull example, JSR-305 is a set of annotations to enhance software defect detection, and includes @NonNull and @CheckForNull and a host of others.

编辑:Project Lombok 正好解决了 getter 和设置器生成.

Edit: Project Lombok solves exactly the problem of getter and setter generation.

这篇关于有没有办法在 Java 中使用注释来替换访问器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:获取对象字段以前的值休眠JPA 下一篇:在 Annotation Processor for java 中发现方法调用的类

相关文章