本文翻译自:How are Anonymous inner classes used in Java?
What is the use of anonymous classes in Java? Java中匿名类的用途是什么? Can we say that usage of anonymous class is one of the advantages of Java? 我们可以说使用匿名类是Java的优势之一吗?
#1楼
参考:https://stackoom.com/question/1UOV/Java中如何使用匿名内部类
#2楼
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: 例如:
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
});
#3楼
One of the major usage of anonymous classes in class-finalization which called finalizer guardian . 匿名类在类最终确定中的主要用法之一称为finalizer Guardian 。 In Java world using the finalize methods should be avoided until you really need them. 在Java世界中,应避免使用finalize方法,直到您真正需要它们为止。 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. 您必须记住,当为子类覆盖finalize方法时,您也应该始终调用super.finalize()
,因为超类的finalize方法不会自动调用,并且您可能会遇到内存泄漏的麻烦。
so considering the fact mentioned above, you can just use the anonymous classes like: 因此,考虑到上述事实,您可以只使用匿名类,例如:
public class HeavyClass{
private final Object finalizerGuardian = new Object() {
@Override
protected void finalize() throws Throwable{
//Finalize outer HeavyClass object
}
};
}
Using this technique you relieved yourself and your other developers to call super.finalize()
on each sub-class of the HeavyClass
which needs finalize method. 使用此技术,您和其他开发人员都HeavyClass
在需要finalize方法的HeavyClass
每个子类上调用super.finalize()
。
#4楼
new Thread() {
public void run() {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
System.out.println("Exception message: " + e.getMessage());
System.out.println("Exception cause: " + e.getCause());
}
}
}.start();
This is also one of the example for anonymous inner type using thread 这也是使用线程匿名内部类型的示例之一
#5楼
i use anonymous objects for calling new Threads.. 我使用匿名对象调用新线程。
new Thread(new Runnable() {
public void run() {
// you code
}
}).start();
#6楼
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. 但是应谨慎使用,因为这会给程序的可读性带来问题。