Java中如何使用匿名内部类?
Java中匿名类有什么用? 我们可以说使用匿名类是Java的优点之一吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
Java中匿名类有什么用? 我们可以说使用匿名类是Java的优点之一吗?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(19)
这里似乎没有人提到,但您也可以使用匿名类来保存泛型类型参数(通常由于类型擦除而丢失):
如果您以匿名方式实例化此类
,那么这样的
holder< /code> 实例将包含传递类型的非擦除定义。
用法
这对于构建验证器/反序列化器非常方便。 您还可以使用反射实例化泛型类型(因此,如果您想在参数化类型中执行 new T() - 欢迎您!)。
缺点/限制
Seems nobody mentioned here but you can also use anonymous class to hold generic type argument (which normally lost due to type erasure):
If you'll instantiate this class in anonymous way
then such
holder
instance will contain non-erasured definition of passed type.Usage
This is very handy for building validators/deserializators. Also you can instantiate generic type with reflection (so if you ever wanted to do
new T()
in parametrized type - you are welcome!).Drawbacks/Limitations
匿名内部类用于创建永远不会再次引用的对象。 它没有名称,并且在同一语句中声明和创建。
这用在通常使用对象变量的地方。 您可以将变量替换为
new
关键字、对构造函数的调用以及{
和}
中的类定义。当用 Java 编写线程程序时,通常看起来像这样。
这里使用的 ThreadClass 是用户定义的。 此类将实现创建线程所需的 Runnable 接口。 在
ThreadClass
中,还需要实现run()
方法(仅在Runnable
中的方法)。很明显,摆脱 ThreadClass 会更有效,这正是匿名内部类存在的原因。
查看以下代码
此代码替换了最上面示例中对
task
的引用。Thread()
构造函数内的匿名内部类没有使用单独的类,而是返回一个实现Runnable
接口并覆盖run()< 的未命名对象。 /代码> 方法。 run() 方法将包含执行线程所需工作的语句。
回答匿名内部类是否是Java的优点之一的问题时,我不得不说我不太确定,因为我目前对许多编程语言都不熟悉。 但我可以说的是,这绝对是一种更快、更简单的编码方法。
参考文献:Sams 《21 天自学 Java》第七版
An Anonymous Inner Class is used to create an object that will never be referenced again. It has no name and is declared and created in the same statement.
This is used where you would normally use an object's variable. You replace the variable with the
new
keyword, a call to a constructor and the class definition inside{
and}
.When writing a Threaded Program in Java, it would usually look like this
The
ThreadClass
used here would be user defined. This class will implement theRunnable
interface which is required for creating threads. In theThreadClass
therun()
method (only method inRunnable
) needs to be implemented as well.It is clear that getting rid of
ThreadClass
would be more efficient and that's exactly why Anonymous Inner Classes exist.Look at the following code
This code replaces the reference made to
task
in the top most example. Rather than having a separate class, the Anonymous Inner Class inside theThread()
constructor returns an unnamed object that implements theRunnable
interface and overrides therun()
method. The methodrun()
would include statements inside that do the work required by the thread.Answering the question on whether Anonymous Inner Classes is one of the advantages of Java, I would have to say that I'm not quite sure as I am not familiar with many programming languages at the moment. But what I can say is it is definitely a quicker and easier method of coding.
References: Sams Teach Yourself Java in 21 Days Seventh Edition
优化代码的最佳方法。 另外,我们可以用于类或接口的重写方法。
The best way to optimize code. also, We can use for an overriding method of a class or interface.
还有一个优势:
如您所知,Java 不支持多重继承,因此,如果您使用“Thread”类作为匿名类,那么该类仍然留有一个空间供任何其他类扩展。
One more advantage:
As you know that Java doesn't support multiple inheritance, so if you use "Thread" kinda class as anonymous class then the class still has one space left for any other class to extend.
我发现 该问题的答案(重复) 是对于这个问题的回答非常简洁。
这是我的笔记。
对于一个用例:
它等同于:
更简洁的简写:
与...一样:
和 ...
这就是关于 java 中的匿名子类的所有要点。
I found that answer with its question (which is duplicated) is a very terse reply for this question.
Here are my notes.
For a use case:
It's same as:
More succinct shorthand:
same as:
And ...
And that's all important points about the anonymous subclass mean in java.
通过“匿名类”,我认为你的意思是 匿名内部类。
当使用某些“额外”(例如重写方法)创建对象实例时,匿名内部类会很有用,而不必实际子类化一个类。
我倾向于使用它作为附加事件侦听器的快捷方式:
使用此方法可以使编码更快一些,因为我不需要创建一个实现
ActionListener
的额外类 - 我可以实例化一个匿名内部类,而不实际创建一个单独的类。我只将这种技术用于“快速而肮脏”的任务,在这些任务中,让整个班级感觉没有必要。 拥有多个执行完全相同操作的匿名内部类应该重构为实际的类,无论是内部类还是单独的类。
By an "anonymous class", I take it you mean anonymous inner class.
An anonymous inner class can come useful when making an instance of an object with certain "extras" such as overriding methods, without having to actually subclass a class.
I tend to use it as a shortcut for attaching an event listener:
Using this method makes coding a little bit quicker, as I don't need to make an extra class that implements
ActionListener
-- I can just instantiate an anonymous inner class without actually making a separate class.I only use this technique for "quick and dirty" tasks where making an entire class feels unnecessary. Having multiple anonymous inner classes that do exactly the same thing should be refactored to an actual class, be it an inner class or a separate class.
匿名内部类实际上是闭包,因此它们可用于模拟 lambda 表达式或“委托”。 例如,采用此接口:
您可以匿名使用此接口来创建一流函数在爪哇。 假设您有以下方法,它返回给定列表中第一个大于 i 的数字,如果没有数字更大,则返回 i:
然后您还有另一个方法,返回给定列表中第一个小于 i 的数字,如果没有则返回 i没有更小的数字:
这些方法几乎相同。 使用第一类函数类型 F,我们可以将它们重写为一个方法,如下所示:
您可以使用匿名类来使用 firstMatch 方法:
这是一个非常人为的示例,但很容易看出能够传递函数就好像它们是值一样是一个非常有用的功能。 请参阅 Joel 本人的“你的编程语言能做到这一点吗”。
一个很好的库,用于以这种风格进行 Java 编程:Functional Java。
Anonymous inner classes are effectively closures, so they can be used to emulate lambda expressions or "delegates". For example, take this interface:
You can use this anonymously to create a first-class function in Java. Let's say you have the following method that returns the first number larger than i in the given list, or i if no number is larger:
And then you have another method that returns the first number smaller than i in the given list, or i if no number is smaller:
These methods are almost identical. Using the first-class function type F, we can rewrite these into one method as follows:
You can use an anonymous class to use the firstMatch method:
This is a really contrived example, but its easy to see that being able to pass functions around as if they were values is a pretty useful feature. See "Can Your Programming Language Do This" by Joel himself.
A nice library for programming Java in this style: Functional Java.
匿名内部类用于以下场景:
1.) 对于覆盖(子类化),当类定义除当前情况外不可用时:
2.) 对于实现接口,当仅在当前情况下需要实现接口时:
3.)参数定义匿名内部类:
Anonymous inner class is used in following scenario:
1.) For Overriding(subclassing), when class definition is not usable except current case:
2.) For implementing an interface, when implementation of interface is required only for current case:
3.) Argument Defined Anonymous inner class:
我有时使用它们作为 Map 实例化的语法技巧:
vs
在执行大量 put 语句时它可以节省一些冗余。 但是,当外部类需要通过远程处理进行序列化时,我在执行此操作时也遇到了问题。
I use them sometimes as a syntax hack for Map instantiation:
vs
It saves some redundancy when doing a lot of put statements. However, I have also run into problems doing this when the outer class needs to be serialized via remoting.
它们通常用作回调的详细形式。
我想你可以说与没有它们相比,它们是一个优势,并且每次都必须创建一个命名类,但是类似的概念在其他语言中实现得更好(作为闭包或块)
这是一个摇摆示例
虽然它仍然很混乱冗长,这比强迫您为每个丢弃的侦听器定义一个命名类要好得多(尽管根据情况和重用,这可能仍然是更好的方法)
They're commonly used as a verbose form of callback.
I suppose you could say they're an advantage compared to not having them, and having to create a named class every time, but similar concepts are implemented much better in other languages (as closures or blocks)
Here's a swing example
Although it's still messily verbose, it's a lot better than forcing you to define a named class for every throw away listener like this (although depending on the situation and reuse, that may still be the better approach)
您可以在需要在另一个函数中创建一个用于特定目的的类的情况下使用它,例如,作为侦听器、作为可运行对象(以生成线程)等。
其想法是从代码内部调用它们一个函数,这样您就永远不会在其他地方引用它们,因此您不需要命名它们。 编译器只是枚举它们。
它们本质上是语法糖,随着它们变大,通常应该转移到其他地方。
我不确定这是否是 Java 的优点之一,但如果您确实使用它们(不幸的是,我们都经常使用它们),那么您可以说它们就是其中之一。
You use it in situations where you need to create a class for a specific purpose inside another function, e.g., as a listener, as a runnable (to spawn a thread), etc.
The idea is that you call them from inside the code of a function so you never refer to them elsewhere, so you don't need to name them. The compiler just enumerates them.
They are essentially syntactic sugar, and should generally be moved elsewhere as they grow bigger.
I'm not sure if it is one of the advantages of Java, though if you do use them (and we all frequently use them, unfortunately), then you could argue that they are one.
匿名类指南。
匿名类同时声明和初始化。
匿名类必须扩展或实现一个且仅一个类或接口。
由于匿名类没有名称,因此只能使用一次。
例如:
GuideLines for Anonymous Class.
Anonymous class is declared and initialized simultaneously.
Anonymous class must extend or implement to one and only one class or interface resp.
As anonymouse class has no name, it can be used only once.
eg:
是的,匿名内部类绝对是Java的优点之一。
使用匿名内部类,您可以访问周围类的最终变量和成员变量,这在侦听器等中派上用场。
但一个主要优点是内部类代码(至少应该)与周围的类/方法/块,具有特定的上下文(周围的类、方法和块)。
Yes, anonymous inner classes is definitely one of the advantages of Java.
With an anonymous inner class you have access to final and member variables of the surrounding class, and that comes in handy in listeners etc.
But a major advantage is that the inner class code, which is (at least should be) tightly coupled to the surrounding class/method/block, has a specific context (the surrounding class, method, and block).
这也是使用线程的匿名内部类型的示例之一
This is also one of the example for anonymous inner type using thread
内部类与外部类的实例关联有两种特殊类型:本地类和匿名类 。 匿名类使我们能够同时声明和实例化一个类,从而使代码简洁。 当我们只需要一次本地类时,我们会使用它们,因为它们没有名称。
考虑 doc 中的示例,其中我们有一个
Person
类:我们有一个方法来打印与搜索条件匹配的成员,如下所示:
其中
CheckPerson
是一个接口,如下所示:现在我们可以利用实现此接口的匿名类来指定搜索标准为:
这里的接口非常简单,匿名类的语法似乎笨拙且不清楚。
Java 8引入了一个术语函数式接口这是一个只有一个抽象方法的接口,因此我们可以说
CheckPerson
是一个函数式接口。 我们可以利用 Lambda 表达式 它允许我们通过函数作为方法参数为:我们可以使用标准函数接口
Predicate
来代替接口CheckPerson
,这将进一步减少所需的代码量。An inner class is associated with an instance of the outer class and there are two special kinds: Local class and Anonymous class. An anonymous class enables us to declare and instantiate a class at same time, hence makes the code concise. We use them when we need a local class only once as they don't have a name.
Consider the example from doc where we have a
Person
class:and we have a method to print members that match search criteria as:
where
CheckPerson
is an interface like:Now we can make use of anonymous class which implements this interface to specify search criteria as:
Here the interface is very simple and the syntax of anonymous class seems unwieldy and unclear.
Java 8 has introduced a term Functional Interface which is an interface with only one abstract method, hence we can say
CheckPerson
is a functional interface. We can make use of Lambda Expression which allows us to pass the function as method argument as:We can use a standard functional interface
Predicate
in place of the interfaceCheckPerson
, which will further reduce the amount of code required.我使用匿名对象来调用新线程..
i use anonymous objects for calling new Threads..
匿名内部类在为不同对象提供不同实现时可能很有用。 但应该非常谨慎地使用,因为它会给程序可读性带来问题。
Anonymous inner class can be beneficial while giving different implementations for different objects. But should be used very sparingly as it creates problem for program readability.
匿名类在类终结中的主要用法之一称为终结器守护者。 在 Java 世界中,应该避免使用 Finalize 方法,直到真正需要它们为止。 你必须记住,当你重写子类的finalize方法时,你应该总是调用
super.finalize()
,因为超类的finalize方法不会自动调用,你可以遇到内存泄漏问题。因此,考虑到上述事实,您可以使用匿名类,例如:
使用这种技术,您可以减轻自己和其他开发人员在
的每个子类上调用
需要 Finalize 方法。super.finalize()
的负担。 HeavyClassOne of the major usage of anonymous classes in class-finalization which called finalizer guardian. In Java world using the finalize methods should be avoided until you really need them. You have to remember, when you override the finalize method for sub-classes, you should always invoke
super.finalize()
as well, because the finalize method of super class won't invoke automatically and you can have trouble with memory leaks.so considering the fact mentioned above, you can just use the anonymous classes like:
Using this technique you relieved yourself and your other developers to call
super.finalize()
on each sub-class of theHeavyClass
which needs finalize method.您可以通过这种方式使用匿名类
You can use anonymous class this way