在 Java 中使用匿名类是不好的还是好的?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/487126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 12:36:55  来源:igfitidea点击:

Is usage of anonymous classes in Java considered bad style or good?

javacoding-styleanonymous-class

提问by Mnementh

I know anonymous classes save typing when it comes to implementing Listener and similar stuff. They try to be a replacement for some usages of closures.

我知道匿名类在实现 Listener 和类似的东西时可以节省输入。他们试图替代闭包的某些用法。

But what does the community think about the value of this language-feature? Does it make sense and do you use it regularly? Does it make the code clearer, more understandable and more maintainable? Or do anonymous classes make the code less readable?

但是社区如何看待这种语言功能的价值?它有意义吗?您是否经常使用它?它是否使代码更清晰、更易于理解和更易于维护?还是匿名类会使代码的可读性降低?

What is your opinion, and please have examples/arguments handy to support your opinion?

您的观点是什么,请提供方便的例子/论据来支持您的观点?

采纳答案by coobird

I tend to use anonymous inner classes in situations where I don't need to have a full-blown class just to perform some task. For example, if I want to implement an ActionListeneror Runnable, but I don't think having an inner class would be necessary. For example, for starting a simple Thread, using an anonymous inner class might be more readable:

我倾向于在不需要为了执行某些任务而拥有完整类的情况下使用匿名内部类。例如,如果我想实现一个ActionListeneror Runnable,但我认为不需要内部类。例如,为了开始一个 simple Thread,使用匿名内部类可能更具可读性:

public void someMethod()
{
    new Thread(new Runnable() {
        public void run()
        {
            // do stuff
        }
    }).start();
}

In certain cases, such as the example above, it can increase readability, especially for one-time tasks, as the code that is to be executed is all written in one spot. Using an inner class would "delocalize" the code:

在某些情况下,例如上面的示例,它可以提高可读性,尤其是对于一次性任务,因为要执行的代码全部写在一个地方。使用内部类会使代码“非本地化”:

public void someMethod()
{
    new Thread(new MyRunnable()).start();
}

// ... several methods down ... //

class MyRunnable implements Runnable
{
    public void run()
    {
        // do stuff
    }
}

That said, however, if there is going to be cases where the same thing is going to be repeated, it should indeed be a separate class, be it a regular class or an inner class.

话虽如此,但是,如果要重复相同的事情,它确实应该是一个单独的类,无论是常规类还是内部类。

I tend to use anonymous inner classes in programs where I am just trying things out rather than have it as a central feature of an actual application.

我倾向于在程序中使用匿名内部类,在这些程序中我只是尝试一些东西,而不是将其作为实际应用程序的核心功能。

回答by Priyank Doshi

One more good use of anonymous inner class is when you need to initialize collections like ArrayList and Set. This practice is also known as double brace initializationFor example ,

匿名内部类的另一个很好的用途是当您需要初始化像 ArrayList 和 Set 这样的集合时。这种做法也称为双括号初始化,例如,

private static final Set<String> VALID_CODES = new HashSet<String>() {{
add("XZ13s");
add("AB21/X");
add("YYLEX");
add("AR2D");
}};

Obviously, this is not limited to collections; it can be used to initialize any kind of object -- for example Gui objects:

显然,这不仅限于集合;它可用于初始化任何类型的对象——例如 Gui 对象:

 add(new JPanel() {{
setLayout(...);
setBorder(...);
add(new JLabel(...));
add(new JSpinner(...));
}});

回答by DonX

My opinion is anonymous classes makes the code less readable. For implementing listeners anonymous classes are useful. For developing a GWTapplication anonymous classes are the better choice. For these cases, if we are not using anonymous classes then the number of lines of code will increase.

我的观点是匿名类会降低代码的可读性。对于实现侦听器匿名类很有用。对于开发GWT应用程序,匿名类是更好的选择。对于这些情况,如果我们不使用匿名类,那么代码行数将会增加。

回答by boutta

We use anonymous classes regurlarly. I find them easy to use for implementing interfaces that have only one or two methods and that where the functionality isn'tused anywhere else. If you use the same functionality again somewhere else there should be a real class to be reused.

我们定期使用匿名类。我发现它们易于用于实现只有一种或两种方法且功能在其他任何地方使用的接口。如果您在其他地方再次使用相同的功能,应该有一个真正的类可以重用。

回答by Peewhy

Whether using anonymous class improves or degrades legibility is a matter of taste. The main issue is definitely not here.

使用匿名类是提高还是降低易读性是一个品味问题。主要问题肯定不在这里。

Anonymous classes, like inner classes, carries a reference to the enclosing class, thus making non private things that without it would be. To be short, the thisreference of the enclosing class may escape through the inner class. So the answer is: it is a very bad practice to use an inner class if it published itself, since that would automatically publish the enclosing class. for example:

匿名类,像内部类一样,带有对封闭类的引用,从而使没有它的东西成为非私有的。简而言之,封闭类的this引用可能会通过内部类逃逸。所以答案是:如果内部类发布自己,那么使用内部类是一种非常糟糕的做法,因为这会自动发布封闭类。例如:

changeManager.register(new ChangeListener() {
    public void onChange(...) {
       ...
    }});

Here, the anonymous ChangeLsteneris passed to the registermethod of a ChangeManager. Doing so will automatically publish the enclosing class as well.

在这里,匿名ChangeLstener被传递给ChangeManagerregister方法。这样做也会自动发布封闭类。

This is definitely a bad practice.

这绝对是一种不好的做法。

回答by Bombe

I use anonymous classes mostly for interfaces that have only a single method, i.e. Runnableor ActionListener. Most larger interfaces warrent their own classes or implementation in an already existing class. And as it is my opinion I don't need arguments to support it.

我主要将匿名类用于只有一个方法的接口,即RunnableActionListener。大多数较大的接口在已经存在的类中保护它们自己的类或实现。因为这是我的观点,所以我不需要论据来支持它。

回答by Sajol

Anonymous class is mostly seen in GUI application specially for events handling.Anonymous class is useful in cases of implementing small interfaces that contains one or two methods..For example.. you have a class where you have two or three threads and you want to perform two or three different tasks using those threads.In this situation you can take the help of anonymous class to perform your desired tasks. look at the follow example

匿名类主要出现在 GUI 应用程序中,专门用于事件处理。匿名类在实现包含一两个方法的小接口的情况下很有用。使用这些线程执行两个或三个不同的任务。在这种情况下,您可以借助匿名类来执行您想要的任务。看下面的例子

class AnonymousClass{

public static void main(String args[]){


    Runnable run1=new Runnable(){

        public void run(){

            System.out.println("from run1");
        }

    };
    Runnable run2=new Runnable(){

        public void run(){

            System.out.println("from run2");
        }

    };
    Runnable run3=new Runnable(){

        public void run(){

            System.out.println("from run3");
        }

    };



    Thread t1=new Thread(run1);
    Thread t2=new Thread(run2);
    Thread t3=new Thread(run3);


    t1.run();t2.run();t3.run();

}
}

output:

输出:

from run1

from run2

from run3

从运行 1

从运行 2

从运行 3

In the above snap of code i have used three threads to perform three different tasks. Look i have created three anonymous classes that contains the implementation of the run method to perform three different small tasks.

在上面的代码快照中,我使用了三个线程来执行三个不同的任务。看,我创建了三个匿名类,其中包含 run 方法的实现以执行三个不同的小任务。

回答by Stephen Denne

It depends what you compare them to. I'd rather have them than not have them, but then I'd rather be able to supply plain code blocks to methods like Arrays.sort() than having to explicitly create a class containing my implementation of compare().

这取决于您将它们与什么进行比较。我宁愿拥有它们也不愿没有它们,但是我宁愿能够为 Arrays.sort() 之类的方法提供纯代码块,而不必显式创建一个包含我的 compare() 实现的类。

回答by Megacan

It makes sense to use them, but you must be aware of whats being done underneath. I only use them if I need a class to do something very specific that I don't need anywhere else.

使用它们是有意义的,但你必须知道在下面做了什么。我只在需要一个班级来做一些我在其他任何地方都不需要的非常具体的事情时才使用它们。

回答by duffymo

If limiting scope and access as much as possible is a good thing, then anonymous classes are very good. They are limited in scope to the one class that needs them. When that's appropriate, I'd say anonymous classes are good.

如果尽可能地限制范围和访问是一件好事,那么匿名类非常好。它们的范围仅限于需要它们的一类。在适当的时候,我会说匿名类很好。

The instant you duplicate the same function, it becomes a bad idea. Refactor it into a public class that stands on its own. IDEs with refactoring features make that easy.

一旦你复制相同的功能,它就变成了一个坏主意。将其重构为一个独立的公共类。具有重构功能的 IDE 使这一切变得容易。