Java中的方法参数中的类定义? [英] Class definition inside method argument in Java?

查看:302
本文介绍了Java中的方法参数中的类定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第一次遇到这种形式的Java代码:

  object.methodA(new ISomeName 
public void someMethod(){
// some code
}
});

其中ISomeName是一个接口,它具有与上述someMethod()相同的签名。 p>

从我可以理解的是,我们定义一个新的类实现ISomeName,使用默认构造函数创建一个类的对象,并将对象作为参数传递给methodA。 / p>

这是否正确?



此功能的名称是什么?

解决方案

正在创建 匿名类别



请注意,类,可以从方法的早期代码中引用最终局部变量,包括最终参数:

  final String name = getName(); 

Thread t = new Thread(new Runnable(){
@Override public void run(){
System.out.println(name);
}
});
t.start();

变量的会传递到匿名类的构造函数。这是一种薄弱的 关闭 (由于限制:只复制值,这就是为什么变量必须是final)。


I have come across Java code in this form for the first time:

object.methodA(new ISomeName() {
public void someMethod() {
//some code
}
});

Where ISomeName is an interface that has one method with the same signature as someMethod() above.

From what I can understand, we are defining a new nameclass class that implements ISomeName, creating an object of this class using default constructor and passing the object as an argument to methodA.

Is this right?

What is the name of this feature?

解决方案

It's creating an anonymous class.

Note that within anonymous class, you can refer to final local variables from within the earlier code of the method, including final parameters:

final String name = getName();

Thread t = new Thread(new Runnable() {
    @Override public void run() {
        System.out.println(name);
    }
});
t.start();

The values of the variables are passed into the constructor of the anonymous class. This is a weak form of closures (weak because of the restrictions: only values are copied, which is why the variable has to be final).

这篇关于Java中的方法参数中的类定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆