Java:为什么在定义字段之前引用字段时没有警告?

编程入门 行业动态 更新时间:2024-10-14 18:19:05
本文介绍了Java:为什么在定义字段之前引用字段时没有警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在定义或初始化静态字段之前,无法对其进行引用:

A static field cannot be referenced before it is defined or initialized:

static Integer j = i; /* compile error */ static final Integer i = 5;

但是,当从实例初始化块(在匿名内部类中)对其进行引用时,甚至不会生成警告.

However, when it is referenced from an instance initialization block (in an anonymous inner class), not even a warning is generated.

查看示例:

class StaticInitialization { static final Object o = new Object() {{ j = i; }}; static Integer j, k; static final Integer i = 5; static final Object o2 = new Object() {{ k = i; }}; }

结果是:j == null,k == 5,因此很显然,我们已进行了参考,订单很重要,没有警告或编译错误.

The result is: j == null, k == 5, so clearly we've made a reference, order matters, and no warning or compilation error.

此代码合法吗?

推荐答案

此代码合法吗?大概.我不认为分析对象实例化在调试静态变量时故意产生的副作用不是编译器的工作.

Is this code legal? Probably. I don't think it's the compiler's job to analyze your deliberate side-effects of object instantiation in buggering up static variables.

对同一类中其他静态变量的引用之前声明"的有限分析实际上只是对最常见的boo-boos的帮助,而不是对间接错误的坚定保证.

The limited analysis of 'declare before referencing' from other statics in the same class is really just a helper against the most common boo-boos, not a ironclad guarantee against indirect errors.

对于引用之前的声明"分析的范围仅限于直接访问其他static声明中的静态变量,我真的不感到惊讶.这是一个简单的&紧凑的分析,具有最小的复杂度和非常快.

I'm really not at all surprised that the the "declare before referencing" analysis is limited in scope to direct access of static variables in other static declarations. This is a simple & compact analysis with minimal complexity & very fast.

扩展它以考虑对象实例化的副作用方法调用OTOH将需要增加20-1000倍的重量&静态程序分析的范围.静态分析要求访问潜在的整个编译程序代码,并使用基于约束的计算来确定可能发生的情况以及运行时间(可能在几分钟内).

Extending it to consider side-effects of object instantiation & method calls, OTOH, would require the 20-1000x greater weight & scope of static program analysis. Static analysis requires access to potentially the entire compiled program code, with constraint-based computation to determine what may possibly happen, and run-times potentially in the minutes.

考虑到这些选择,在Java语言设计者的眼中,选择简单分析非常简单,该分析仅涵盖来自同一类内字段的直接访问.

Given these choices it is fairly easy, in the Java language designer's shoes, to choose simple analysis covering only direct accesses from fields within the same class.

更多推荐

Java:为什么在定义字段之前引用字段时没有警告?

本文发布于:2023-11-27 13:09:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1638206.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   定义   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!