java - 是否可以在 Java 中将匿名内部类设为静态?

标签 java syntax inner-classes

在Java 中,嵌套类可以是static,也可以不是。如果它们是static,则它们不包含对包含实例的指针的引用(它们也不再被称为内部类,它们被称为嵌套类)。

在不需要引用时忘记创建嵌套类 static 可能会导致垃圾收集或逃逸分析出现问题。

是否也可以制作匿名内部类static?还是编译器会自动解决这个问题(它可以,因为不能有任何子类)?

例如,如果我做一个匿名比较器,我几乎不需要对外部的引用:

  Collections.sort(list, new Comparator<String>(){
       int compare(String a, String b){
          return a.toUpperCase().compareTo(b.toUpperCase());
       }
  }

最佳答案

不,你不能,不,编译器无法弄清楚。这就是为什么 FindBugs 总是建议将匿名内部类更改为命名的 static 嵌套类,如果它们不使用它们的隐式 this 引用。

编辑: Tom Hawtin - tackline 说如果匿名类是在静态上下文中创建的(例如在 main 方法中),那么匿名类实际上是 静态。但是 JLS disagrees :

An anonymous class is never abstract (§8.1.1.1). An anonymous class is always an inner class (§8.1.3); it is never static (§8.1.1, §8.5.1). An anonymous class is always implicitly final (§8.1.1.2).

Roedy Green 的 Java 词汇表 says that允许在静态上下文中使用匿名类这一事实取决于实现:

If you want to baffle those maintaining your code, wags have discovered javac.exe will permit anonymous classes inside static init code and static methods, even though the language spec says than anonymous classes are never static. These anonymous classes, of course, have no access to the instance fields of the object. I don’t recommend doing this. The feature could be pulled at any time.

编辑 2: JLS 实际上在 §15.9.2 中更明确地涵盖了静态上下文。 :

Let C be the class being instantiated, and let i be the instance being created. If C is an inner class then i may have an immediately enclosing instance. The immediately enclosing instance of i (§8.1.3) is determined as follows.

  • If C is an anonymous class, then:
    • If the class instance creation expression occurs in a static context (§8.1.3), then i has no immediately enclosing instance.
    • Otherwise, the immediately enclosing instance of i is this.

因此,静态上下文中的匿名类大致相当于 static 嵌套类,因为它不保留对封闭类的引用,即使它在技术上不是 static 类。

关于java - 是否可以在 Java 中将匿名内部类设为静态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/758570/

相关文章:

java - 如何在 Web 服务中返回 HTTP 代码

java - 具有共同偏好的不当行为

Java代码删除文件的初始行执行速度非常慢

java - selenium grid 指定平台

syntax - 这种范围的用法有什么问题?

c++ - std::array :通过智能指针访问元素的成员

共同 friend 类的 C# 解决方法

php - 无效查询 : You have an error in your SQL syntax; syntax to use near

python - 返回函数内部类的 Python 对象实例