且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

大型内部类和私有变量

更新时间:2023-02-15 20:10:23

在字节码级别上,内部类只是普通的Java类.由于Java字节码验证程序不允许访问私有成员,因此它将为您使用的每个私有字段生成综合访问器方法.另外,为了将内部类与其封闭的实例链接起来,编译器将合成指针添加到外部"this".

On bytecode level inner classes are just plain Java classes. Since the Java bytecode verifier does not allow access to private members, it generates synthetic accessor methods for each private field which you use. Also, in order to link the inner class with its enclosing instance, the compiler adds synthetic pointer to the outer 'this'.

考虑到这一点,内部类只是语法糖的一层.它们很方便,您已经列出了一些要点,所以我将列出一些您可能要考虑的负面方面:

Considering this, the inner classes are just a layer of syntax sugar. They are convenient and you have listed some good points, so I'd list some negative aspects which you might want to consider:

  • 您的内部类对整个父类具有隐藏的依赖关系,该父类混淆了其入站接口.如果将其提取为package-private类,则有机会改善设计并使其更易于维护.最初它比较冗长,但通常您会发现:
    • 您实际上不想共享10个访问器,而是希望共享一个值对象.通常,您会发现实际上并不需要引用整个外部类.这也适用于IoC.
    • 与其提供显式锁定方法,不如将操作及其上下文封装在一个单独的类中(或将其移至两个类之一(外部或以前是内部)),这样更易​​于维护.
    • 便利方法属于软件包专用实用程序类.您可以使用Java5静态导入使它们显示为本地.
    • Your inner class has a hidden dependency to the whole parent class, which obfuscates its inbound interface. If you extract it as package-private class you have a chance to improve your design and make it more maintainable. Initially it's more verbose, but often you'd find that:
      • Instead of exposing 10 accessors you actually want to share a single value object. Often you would find that you don't really need a reference to the whole outer class. This also works well with IoC.
      • Instead of providing methods for explicit locking, it's more maintainable to encapsulate the operation with its context in a separate class (or move it to one of the two classes - outer or formerly-inner).
      • Convenience methods belong in package private utility classes. You can use the Java5 static import to make them appear as local.

      P.S.我说的是非平凡的内部类(尤其是那些没有实现任何接口的内部类).三行侦听器实现是好的.

      P.S. I'm talking about non-trivial inner classes (especially ones that do not implement any interfaces). Three line listener implementations are good.