简体   繁体   English

有用的 Java 注释

[英]Useful Java Annotations

I'm interested in finding out exactly which Java annotations people think are most useful during development.我有兴趣确切地找出人们认为在开发过程中最有用的Java 注释 This doesn't necessarily have to limited to the core Java API, you may include annotations you found in third party libraries or annotations you've developed yourself (make sure you include a link to the source).这不一定限于核心 Java API,您可以包含在第三方库中找到的注释或您自己开发的注释(确保包含指向源的链接)。

I'm really interested in common development tasks rather than knowing why the @ManyToOne(optional=false) in JPA is awesome...我真的对常见的开发任务感兴趣,而不是知道为什么 JPA 中的@ManyToOne(optional=false)很棒......

Include the annotation and a description of why it's useful for general development.包括注释和说明为什么它对一般开发有用。

I doled out a bunch of upvotes for other users, but just to give my two cents the only three annotations I use with any regularity in development are the main annotations used directly by the compiler:我为其他用户投了一堆赞成票,但为了给我 2 美分,我在开发中经常使用的三个注释是编译器直接使用的主要注释:

@Override - Great for making it explicit in your code when you're overriding another method. @Override - 非常适合在您覆盖另一种方法时在代码中明确显示。 Also has the extra benefit of being flagged as a compilation error if you don't override a method the way you think you are (see this other SO post ).如果您没有按照您认为的方式覆盖方法,还有一个额外的好处是被标记为编译错误(请参阅其他 SO 帖子)。 This flag informs the compiler that you're intending to override something, so if you don't (eg you forget an argument in the method signature), the compiler will catch it.此标志通知编译器您打算覆盖某些内容,因此如果您不这样做(例如,您忘记了方法签名中的参数),编译器将捕获它。

@Deprecated - Indicate whatever you're marking as something that should not be used from this point forward. @Deprecated - 指明您标记为从现在开始不应使用的任何内容。 The compiler will generate warnings for use of any code elements you've marked as deprecated.编译器将针对您标记为已弃用的任何代码元素的使用生成警告。 In general, deprecation says "this was in here in the past, but it may go away in a future version."一般而言,弃用表示“这在过去存在,但在未来版本中可能会消失。” Make sure you also use the associated "@deprecated" Javadoc flag in conjunction with this too to tell people what they should use instead.确保您也将相关联的“@deprecated”Javadoc 标志与此结合使用,以告诉人们他们应该使用什么来代替。

@SuppressWarnings - Tell the compiler to suppress specific warnings it would otherwise generate. @SuppressWarnings - 告诉编译器抑制它会生成的特定警告。 This can be useful for things like when you intentionally want to use deprecated methods, you can block out the deprecation warning.当您有意使用已弃用的方法时,这可能很有用,您可以阻止弃用警告。 I tend to use it a lot to block out everyone's favorite "Serialization UID" warning on serializable classes (whether or not you should do that is another debate for another time).我倾向于经常使用它来屏蔽每个人最喜欢的关于可序列化类的“序列化 UID”警告(是否应该这样做,这是另一次辩论)。 Just handy for those cases where you know something you're doing is generating a warning, but you're 100% sure it's the proper behavior you want.对于那些您知道自己正在做的事情正在生成警告的情况,这很方便,但您 100% 确定这是您想要的正确行为。

Look at the Sun Annotations Guide and check out the section "Annotations Used by the Compiler".查看Sun Annotations Guide并查看“编译器使用的注释”部分。 These three are given a fairly lengthy discussion.对这三个进行了相当长的讨论。

The Java Concurrency in Practice annotations Java 并发实践注解

Very useful for describing exactly how your code is or isn't thread safe...对于准确描述您的代码是或不是线程安全的非常有用...

I find the he concurrency-related annotations defined by Brian Goetz in his book "Java Concurrency In Practice" to be very useful:我发现 Brian Goetz 在他的书“Java Concurrency In Practice”中定义的与并发相关的注释非常有用:

  • @GuardedBy @GuardedBy
  • @Immutable @不可变
  • @NotThreadSafe @NotThreadSafe
  • @ThreadSafe @线程安全

They're particularly useful as FindBugs has patterns that use them.它们特别有用,因为 FindBugs 有使用它们的模式。

A jar and documentation is freely available at http://www.javaconcurrencyinpractice.com/ jar 和文档可在http://www.javaconcurrencyinpractice.com/免费获得

@Override has my vote. @Override 有我的投票权。 It makes it instantly clear what your method is about and makes your code more readable.它使您的方法的内容立即变得清晰,并使您的代码更具可读性。

@Test

( JUnit 4 ) It's made writing and understanding test files quite a bit cleaner. ( JUnit 4 ) 它使编写和理解测试文件变得更加清晰。 Plus, the ability to add the expected attribute has saved a few lines of code here and there.另外,添加expected属性的能力在这里和那里节省了几行代码。

@Deprecated

Introduced in Java 5 . 在 Java 5 中引入

  • It helps developers see what's deprecated in IDEs.它可以帮助开发人员了解 IDE 中已弃用的内容。 (Prior to this, most IDEs could still pull a @deprecated out of the javadoc comments for a particular method, but this annotation was a nice way to make it meta-information about the method itself, rather than a comment in documentation.) (在此之前,大多数IDE仍然可以拉@deprecated的特定方法的javadoc注释,但是该注释是一个很好的方法,使有关该方法的本身,而不是在文档评论它的元信息。)
  • It's also used by the compiler to print out warnings when you're using deprecated methods.当您使用不推荐使用的方法时,编译器也使用它来打印警告。

Personally I've been looking at the JSR303 Bean Validation and the annotations it provides, I imagine these will become more commonplace, there's only a few implementations of the JSR so far, but they provide annotations such as:就我个人而言,我一直在研究JSR303 Bean Validation及其提供的注释,我想这些会变得更加普遍,到目前为止只有少数 JSR 实现,但它们提供了注释,例如:

@NotNull private String name;
@NotNull @Size(min = 5, max = 30) private String address;

More info here: http://jcp.org/en/jsr/detail?id=303更多信息: http : //jcp.org/en/jsr/detail?id=303

these should be useful, you can define them in your projects to better communicate intentions:这些应该很有用,您可以在项目中定义它们以更好地传达意图:

  • @ThreadSafe @线程安全
  • @Immutable @不可变
  • @ValueObject @值对象
  • @BagOfFunctions (eg java.util.Collections) @BagOfFunctions(例如 java.util.Collections)
  • etc等等

Here are some Annotations I use in day to day development以下是我在日常开发中使用的一些注释

Spring:春天:

  1. @Autowired - used to Auto wire beans @Autowired - 用于自动连接 bean
  2. @Rollback - If set to true it will rollback all DB operations done inside the test case @Rollback - 如果设置为 true,它将回滚测试用例中完成的所有数据库操作

JUnit:单位:

  1. @Test - Tell that a method is a test case @Test - 告诉一个方法是一个测试用例
  2. @Ignore - If you want to ignore any of the test cases @Ignore - 如果您想忽略任何测试用例
  3. @Before - Code that should run before each test case @Before - 应该在每个测试用例之前运行的代码

JPA: JPA:

  1. @Entity - To tell that a POJO is a JPA Entity @Entity - 说明 POJO 是 JPA 实体
  2. @Column - Map the property to DB column @Column - 将属性映射到 DB 列
  3. @Id - tell that a java property is Primary key @Id - 告诉 java 属性是主键
  4. @EmbeddedId - Used for Composite Primary Keys @EmbeddedId - 用于复合主键
  5. @Transient - This property should not be persisted @Transient - 这个属性不应该被持久化
  6. @Version - Used to manage optimistic locking @Version - 用于管理乐观锁
  7. @NamedQuery - Used to declare Native SQLs @NamedQuery - 用于声明本机 SQL
  8. @OneToMany - One to Many relationship @OneToMany - 一对多关系
  9. @ManyToOne - Many to one Relationship @ManyToOne - 多对一关系

I have included only the most essential ones.You can find details about all the JPA annotations from the following links.我只包含了最重要的部分。您可以从以下链接中找到有关所有 JPA 注释的详细信息。

http://www.oracle.com/technology/products/ias/toplink/jpa/resources/toplink-jpa-annotations.html http://www.oracle.com/technology/products/ias/toplink/jpa/resources/toplink-jpa-annotations.html

http://www.hiberbook.com/ http://www.hiberbook.com/

We started using a compile time tool called lombok ( http://projectlombok.org/ ).我们开始使用名为lombok ( http://projectlombok.org/ ) 的编译时工具。 You annotate classes, members, etc. and methods are automatically generated at compile time.您注释类、成员等,并且在编译时自动生成方法。 It's a great productivity boost and saves hundreds of lines of tedious coding.这是一个巨大的生产力提升,并节省了数百行繁琐的编码。

Do you want a toString() method to be automatically generated?你想自动生成一个toString()方法吗? Just annotate your class with @ToString .只需使用@ToString注释您的类。

Tired of having to define getters and setters for your members?厌倦了必须为您的成员定义 getter 和 setter? Annotate your class with @Getter and / or @Setter and they're automatically added.使用@Getter和/或@Setter注释您的类,它们会自动添加。

Want to have an SLF4J logger to log stuff?想要一个 SLF4J 记录器来记录东西吗? @Slf4j creates a private static final logger for you. @Slf4j为您创建一个私有的静态最终记录器。

@Data
public class MyBean {
    // Getters for x and y, setter for y and constructor with x as arg automatically created!
    // toString() and hashCode() methods are there too!
    private final int x;
    private int y;
}

. .

@Slf4j
public class SomeClass {
    public void doSomething() {
        log.info("I've got log.");
    }
}

Setting it up is very easy: just add a provided maven dependency.设置它非常简单:只需添加一个provided maven 依赖项。 There's also a tiny Eclipse / IntelliJ plugin.还有一个很小的 ​​Eclipse / IntelliJ 插件。

Check out the full list of features there: http://projectlombok.org/features/index.html查看那里的完整功能列表: http : //projectlombok.org/features/index.html

Junit 4 provides very useful annotations. Junit 4提供了非常有用的注释。Here's a tutorial illustrating the usage of annotations to define tests.这是一个教程,说明如何使用注释来定义测试。

eg例如

@Test(expected= IndexOutOfBoundsException.class) public void empty() { 
    new ArrayList<Object>().get(0); 
}

As Dan pointed out below, TestNG did this originally.正如丹在下面指出的那样, TestNG最初是这样做的。

@Given

allows one JUnit test to build upon the return value of another test.允许一个 JUnit 测试建立在另一个测试的返回值上。 Requires JExample .需要JExample

I started a weekend project to implement a Programming By Contract framework using method and parameter annotations eg我开始了一个周末项目,使用方法和参数注释来实现按合同编程框架,例如

//...
myMethod (@NotNull String a, @NotNullOrEmpty String b){
     if ( !validate() ){
         //raiseException
     }
}

I got stuck at the point of getting param values automatically.我陷入了自动获取参数值的问题。 Java reflection does not have it. Java反射没有它。 never understood several people's ranting on Java till I came across this limitation.直到我遇到这个限制,我才明白几个人对 Java 的咆哮。

@FunctionalInterface

Useful to communicate that a particular interface is meant to be functional.用于传达特定接口的功能。 If the single abstract method is removed, it'll throw a compilation error.如果删除单个抽象方法,它将引发编译错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM