有没有办法在 Java 中使用注解来替换访问器? [英] Is there a way to use annotations in Java to replace accessors?

查看:23
本文介绍了有没有办法在 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 中使用注解来替换访问器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆