gpt4 book ai didi

java - 在 Java 中使用@Nullable

转载 作者:太空狗 更新时间:2023-10-29 22:46:33 26 4
gpt4 key购买 nike

我有一个关于在 Java 中使用 @Nullable 注释的问题。

根据我的阅读,设置可能返回空值的方法是一种很好的做法。这样,如果使用@NotNull,IDE 可能会帮助检测一些空指针异常错误或建议删除不必要的空指针异常检查。

到目前为止一切顺利,但是如何使用 @Nullable 作为方法参数呢?这是一个好的做法,还是代码会变得更加冗长(如果与 final 一起使用)并且可能会失去好处,因为您并不总是知道哪些参数将传递给函数调用?另外,您对将 @Nullable 与 setter 方法一起使用有何看法?

用法与在公司工作时的情况有关,而不是与小项目(如家庭作业)有关。

最佳答案

Due to the inherent complexity, flow analysis is best performed in small chunks. Analyzing one method at a time can be done with good tool performance - whereas whole-system analysis is out of scope for the Eclipse Java compiler. The advantage is: analysis is fast and can be done incrementally such that the compiler can warn you directly as you type. The down-side: the analysis can not "see" which values (null or non-null) are flowing between methods (as parameters and return values).

This is where null annotations come into play. By specifying a method parameter as @NonNull you can tell the compiler that you don't want a null value in this position.

Reference

Reference 2

用法:link explains在哪里使用什么注解。

用法 2

Getters/Setters: Yes, it is possible. The Project Lombok (http://projectlombok.org/index.html) defines annotations for generating getters/setters and more.

So for example

@lombok.Data;
public class Person {
private final String name;
private int age;
}

Will generate getter for name (not setter since it is final) and getter/setter for age. It will also generate equals, hashCode, toString and construtor initializing required fields (name). Adding @AllArgsConstructor would generate constructor initializing both fields.

There are other annotations and parameters giving you control over access rights (should your getter be protected or public), names (getName or name?), etc. And there is more. For example, I really like the extension methods.

Lombok is very easy to use. Just download the jar and use the annotations, then the getter/setters can be used in your code without actually being spelled out. Moreover, IDE's like Netbeans support this, so that you see the getter/setter in code completion, navigation, etc. The annotations are used only during compilation not during runtime, so you don't distribute lombok with your jar's.

NotNull: This is supported by findbugs and IdeaJ IDE, maybe others

Reference 3

关于java - 在 Java 中使用@Nullable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22988243/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com