是否有使用注释在Java中,以取代访问的方法吗? [英] Is there a way to use annotations in Java to replace accessors?

查看:117
本文介绍了是否有使用注释在Java中,以取代访问的方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点新的Java 5注释,我很好奇,如果任一这些是可能的:

此标注将生成一个简单的getter和setter你。

  @attribute
私人字符串VAR =;

@NotNull 注释指示变量是粗野,所以空你就不必每次都写样板code。

  / *
 * @参数小号@NotNull
 * /
公共无效了setString(String s)将{
    ...
}

要么这些工作?他们看起来像的第一件事我会写,如果我能注解。因为我没有看到太多关于这些,当我读我假设它不是真的什么注解是有关文档。这里的任何方向将是AP preciated。


解决方案

在抽象语法树时注释处理。这是解析器创建结构和编译器操纵

目前规范(链接来)说,注释处理器不能改变的抽象语法树。一个这样的后果是,它是不适合做code生成。

如果您想这种功能,那么看看 XDoclet的。这应该给你code一代preprocessing我认为你正在寻找。

有关你的 @NonNull 例如, JSR-305 是一个组注解来提升软件缺陷检测,包括 @NonNull @CheckForNull 和其他的主机。

修改的:项目龙目岛解决getter和setter产生的正是问题

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

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

@attribute
private String var = "";

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.

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.

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.

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

这篇关于是否有使用注释在Java中,以取代访问的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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