警告 - 访问静态字段年份
我正在使用日历
来访问当前年份。
这是我的代码...
import java.util.Calendar;
Calendar c = c.getInstance();
int year = c.get(c.YEAR);
代码编译并运行良好,但它显示一条警告消息,指出“警告,访问静态字段”是否有问题,或者我应该做一些更好的事情?
I am using a Calendar
to gain access to the current year.
This is my code...
import java.util.Calendar;
Calendar c = c.getInstance();
int year = c.get(c.YEAR);
The code compiles and runs fine, but it displays a warning message saying "Warning, accessing a static field" Is there something wrong, or should I be doing something better?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
Calendar.getInstance()
和Calendar.YEAR
,不应使用实例对象访问静态字段。Use
Calendar.getInstance()
andCalendar.YEAR
, static fields should not be accessed using instance objects.不要执行
Calendar c = c.getInstance();
,而是执行Calendar c = Calendar.getInstance();
。getInstance()
方法是Calendar
类的静态方法,这就是您收到警告的原因。ADD
Calendar.YEAR
也是如此Instead of doing
Calendar c = c.getInstance();
, do thisCalendar c = Calendar.getInstance();
.The
getInstance()
method is a static method ofCalendar
class and that is why you are getting the warning.ADD
The same goes for
Calendar.YEAR
它会警告您,因为静态字段是使用对象的编译时类型而不是运行时类型访问的,这可能会导致很难发现错误。
示例:
如果没有
static
,它将打印“Hello World”。为了防止这些错误,您应该始终通过声明静态变量的类来访问静态变量,而不是使用实例。编译器会警告您,因为没有充分的理由不使用类名。
It warns you because static fields are accessed using the compile time type and not the runtime type of the object, which can cause hard to find bugs.
Example:
Without the
static
it will print "Hello World".To prevent these bugs you should always access static variables by the class they are declared in instead of using an instance. The compiler warns you since there is no good reason not to use the class-name.
当然,建议更改您的代码。但是,如果您只是想避免更改,请使用方法注释:
@SuppressWarnings(“静态访问”)
Of course it is advisable to change your code. However, if you just want to avoid changes, use method annotation:
@SuppressWarnings("static-access")