匿名内部类显示不正确的修饰符

匿名内部类显示不正确的修饰符

本文介绍了匿名内部类显示不正确的修饰符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,以下代码应已将true打印为输出.

To my understanding, the following code should have printed true as output.

但是,当我运行这段代码时,它正在打印false.

However, when I ran this code it is printing false.

匿名类15.9.5. :

public class Test {
    public static void main(String args[]) {
        Object o = new Object() {
        };
        System.out.println("Annonymous class is final: " + Modifier.isFinal(o.getClass().getModifiers()));
    }
}

为什么这段代码的行为如此?

Why this code is behaving like this ?

推荐答案

请注意,自那时以来,该特定部分的JLS中的措词已发生了显着变化.现在(JLS 11)显示为:

Note that the wording in the JLS of that particular section has changed significantly since then. It now (JLS 11) reads:

15.9.5.匿名类声明:

这种措辞更改是在JLS 9中引入的.匿名类的语义和问题中方法的行为基本上保持不变,目的是避免确切地引起该问题的混淆.

This change in wording was introduced in JLS 9. The semantics of anonymous classes and the behavior of the methods in the question remained mostly unchanged, the intention was to avoid exactly the kind of confusion this question is about.

导致更改的说:

具体地说,匿名类几乎不会在设置ACC_FINAL标志的情况下生成.我们不能在不影响某些序列化客户端的情况下改变这种长期的行为(这是允许的,但是不必要地破坏性).而且,如果没有类文件对语言的修饰符进行编码,我们将无法忠实地实现Class.getModifers(它承诺提供"Java语言修饰符").

Specifically, anonymous classes are almost never generated with the ACC_FINAL flag set. We can't change this longstanding behavior without impacting some serialization clients (this would be permissible, but is unnecessarily disruptive). And we can't faithfully implement Class.getModifers (which promises to provide the "Java language modifiers") without the class files encoding the language's modifiers.

但是,更改 did 实际上在某种程度上改变了语义,并且在此票证中也对此进行了记录,作为可接受的影响:

However, the change did actually change semantics to some degree, and this was also documented in this ticket as an acceptable impact:

这篇关于匿名内部类显示不正确的修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 11:43