Java 新对象 { } 构造
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3688503/
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
new Object { } Construct
提问by andrewheins
In Java, the standard way to create an object is using
在 Java 中,创建对象的标准方法是使用
MyClass name = new MyClass();
I also often see the construct
我也经常看到构造
new MyClass() { /*stuff goes in here*/ };
I've been looking online for a while and can't find a good explanation of what the second construct style does or how it does it.
我已经在网上搜索了一段时间,但找不到关于第二种构造样式的作用或它是如何工作的很好的解释。
Can someone please explain how and why you would use the second construct?
有人可以解释一下您将如何以及为什么使用第二个构造吗?
采纳答案by ZeissS
This construct makes actually two things: 1) It declares an anonymous class which extends the class you use in the constructor and 2) creates an instance of this anonymous class.
这个构造实际上做了两件事:1)它声明了一个匿名类,它扩展了你在构造函数中使用的类;2)创建了这个匿名类的一个实例。
Edit: When using such a construct you can observe the anonymous class by looking at the generated .class
files. There is the normal MyClass.class
file and another one for each anonymous subclass: MyClass$1.class
for the first and so on.
编辑:使用这种构造时,您可以通过查看生成的.class
文件来观察匿名类。MyClass.class
每个匿名子类都有一个普通文件和另一个文件:MyClass$1.class
第一个等等。
回答by Roman
Second construction creates an instance of anonymous class which is a subclass of Class
.
第二个构造创建了一个匿名类的实例,它是 的子类Class
。
回答by Carlos
As others have already said, it creates an instance of an anonymous class, subclassing Class
. Here's an example how it is commonly used:
正如其他人已经说过的,它创建了一个匿名类的实例, subclassing Class
。以下是它的常用示例:
panel.addMouseListener(
new MouseAdapter () {
@Override
public void mouseEntered(MouseEvent e) {
System.out.println(e.toString());
}
}
);
The above code creates an instance of an anonymous class which extends MouseAdapter. In the anonymous class the method mouseEntered
has been overridden to demonstrate that the anonymous class works basically as any other class. This is very convenient and common way to create (usually simple) listeners.
上面的代码创建了一个匿名类的实例,它扩展了 MouseAdapter。在匿名类中,该方法mouseEntered
已被覆盖,以证明匿名类基本上与任何其他类一样工作。这是创建(通常很简单)侦听器的非常方便和常用的方法。
回答by Nathan Hughes
You would use the second construct in the case that you want to make an anonymous class. if you have a method that takes a callback as an argument, you might want to specify the implementation of the callback inline as opposed to giving it a name and putting it in a separate file or declaring it elsewhere in the same file.
如果要创建匿名类,则可以使用第二个构造。如果您有一个将回调作为参数的方法,您可能希望内联指定回调的实现,而不是给它一个名称并将其放在单独的文件中或在同一文件的其他地方声明它。
There's also a trick called double brace initializationwhere you can get around not having syntax for literal maps and lists by using anonymous classes, like this:
还有一个叫做双括号初始化的技巧,你可以通过使用匿名类来避免文字映射和列表的语法,如下所示:
Map map = new HashMap() {{put("foo", 1); put("bar", 2);}};
Here the nested braces create an instance initializer. The object bound to map is not a HashMap, its class is an anonymous class extending HashMap. (That means if you have a PMD rule about classes needing to declare serial uids then it will complain about this.)
这里嵌套的大括号创建了一个实例初始值设定项。map绑定的对象不是HashMap,它的类是扩展HashMap的匿名类。(这意味着如果你有一个关于需要声明串行 uid 的类的 PMD 规则,那么它会抱怨这个。)
回答by ZDL-so
If you want to new a object by a protect constructor from another package, you can use:
如果你想通过另一个包的保护构造函数来新建一个对象,你可以使用:
new Foo() {};
otherwise you will get an access error. It equals anonymous subclass inherited from Foo class.
否则会出现访问错误。它等于从 Foo 类继承的匿名子类。
回答by prasadg
From jdk8 onwards you may have seen different syntax seems like creating an objects while using lambda expressions.
从 jdk8 开始,您可能已经看到不同的语法似乎在使用 lambda 表达式时创建对象。
NOTE:Lambda expressions don't get translated into anonymous inner classes, they use invoke dynamicthat was introduced in Java 7 to execute functional methods.
注意:Lambda 表达式不会转换为匿名内部类,它们使用Java 7 中引入的动态调用来执行函数方法。
For Example:
例如:
public class LambdaSample {
public static void main(String[] args) {
//If implementation is only one statement then {} braces are optional
Runnable oneLineImplRunnable = ()->System.out.println("This is one line lambda expression");
//Multiple statements in the implementation then {} braces are mandatory
Comparator<StudentTest> stdComparator = (StudentTest s1,StudentTest s2)->{
if(s1.getFirstName().equals(s2.getFirstName())) {
return s1.getLastName().compareTo(s2.getLastName());
}else {
return s1.getFirstName().compareTo(s2.getFirstName());
}
};
}
}