简体   繁体   English

在定义之前引用匿名内部类

[英]Referencing an anonymous inner class before its definition

In a different post , I was told that it is wrong to define an anonymous inner class "after" (below) a function which uses it. 另一篇文章中 ,有人告诉我在使用该函数的函数“之后”(下面)定义一个匿名内部类是错误的。 However, something like the below compiles and runs fine: 但是,类似下面的内容可以编译并正常运行:

public class CompTest {

    public static void main(String[] args) {
        TreeSet<Integer> ts = new TreeSet<Integer>(intComp);
        ts.add(1);
        ts.add(2);
        ts.add(3);
        System.out.println(ts.toString());
    }

    private static Comparator<Integer> intComp = new Comparator<Integer>() {
        @Override
        public int compare(Integer i1, Integer i2) {
            return i2.compareTo(i1);
        }
    };

}

What is the official word on this? 官方的话是什么? My guess is that since intComp is static , then it is instantiated once when the class CompTest is "loaded" (not sure exactly how that load takes place since there is only a main method and no CompTest objects are constructed), and therefore when main() needs intComp , it is available regardless of where in the source file it was actually defined. 我的猜测是,由于intCompstatic ,所以当类CompTest被“加载”时,它将实例化一次(由于只有一个主方法并且没有CompTest对象,所以不确定确切的加载方式),因此当main()需要intComp ,无论它在源文件中的实际位置是什么,它都可用。

And even though it does work (for the above reason or even a different one)... is it bad practice? 即使它确实起作用了(出于上述原因,甚至还有其他原因)……这是不好的做法吗?

You are refering to this comment I believe: 我相信您是指此评论:

"The comparator definition should be before the add code – Bryan Glazer" “比较器定义应在添加代码之前– Bryan Glazer”

There is no technical reason to put the intComp declaration before (or after) the main declaration. 没有任何技术原因把intComp声明之前(或之后)的main声明。 It works fine either way. 无论哪种方式,它都可以正常工作。

The only possible reason for putting the comparator earlier is stylistic. 较早放置比较器的唯一可能原因是风格。 That is, the intComp declaration is a static variable , and it is conventional to declare variables at the start of a class. 也就是说, intComp声明是一个静态变量通常在类的开头声明变量。

I'm inclined agree with the style point, but it is a minor issue. 我倾向于同意样式,但这是一个小问题。 Also, if it was me, I'd declare the comparator as final , give it a more meaningful name, and use the "constant" naming style; 另外,如果是我,我将比较器声明为final ,给它一个更有意义的名称,并使用“常量”命名方式; eg INT_COMP (but more meaningful). 例如INT_COMP (但更有意义)。


Re Nambari's comment: Re Nambari的评论:

"I think it is bad practice, anonymous class are for limited scope not for global scope." “我认为这是一种不好的做法,匿名类只适用于有限范围而不是全局范围。”

This is nonsense. 这是无稽之谈。 It is quite common for anonymous classes to be used in this way. 以这种方式使用匿名类非常普遍。 Sure, anonymous classes can also be used in nested scopes ... and that is one of their advantages ... but that in no way means that this pattern is wrong. 当然,匿名类可以在嵌套作用域中使用,这是它们的优点之一,但绝不意味着模式是错误的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM