[英]How to call a specific parent constructor using Lambda?
I am aware of the procedure to use the lambda expression to call the single arg constructor . 我知道使用lambda表达式调用单个arg构造函数的过程。 But not sure how to invoke a constructor with additional arguments (not single arg). 但是不确定如何调用带有附加参数的构造函数(而不是单个arg)。 This can be achieved by using anonymous inner class as denoted in " How to call a specific parent constructor from anonymous inner class? " . 这可以通过使用匿名内部类来实现,如“ 如何从匿名内部类调用特定的父构造函数? ”中所述。 But I am more interested in using the lambda expression. 但是我对使用lambda表达式更感兴趣。
For example: For calling the single arg constructor in Thread class, i can do this 例如:为了在Thread类中调用单个arg构造函数,我可以这样做
Thread t1 = new Thread (() -> {
//do sometask
});
But I could not find a similar way to call the Thread(String name) constructor. 但是我找不到类似的方法来调用Thread(String name)构造函数。
basically I want to do something like below using lambda 基本上我想使用lambda做下面的事情
Thread t2 = new Thread("Thread2") {
@Override
public void run() {
}
};
Any help here is appreciated.Thanks. 感谢您的任何帮助。
I am not sure if I understand the question but if you want to use lambda and string constructor something like this should work: 我不确定我是否理解问题,但是如果您想使用lambda和字符串构造函数,则应该可以执行以下操作:
Thread t2 = new Thread(() -> System.out.println("in "), "Thread2")
Because the constructor in Thread class looks like: 因为Thread类中的构造函数如下所示:
public Thread(Runnable target, String name)
So as the first argument you can use lambda expression (functional interface) and the second argument is the name of the thread. 因此,作为第一个参数,您可以使用lambda表达式(功能接口),第二个参数是线程的名称。
Thread t1 = new Thread (() -> {
//do sometask
}, "ThreadName");
Your second example is not simply calling a constructor. 您的第二个示例不是简单地调用构造函数。 It is defining an anonymous subclass of Thread
, and calling its constructor. 它正在定义Thread
的匿名子类,并调用其构造函数。
Thread t2 = new Thread("Thread2") {
@Override
public void run() {
// do something
}
};
Equivalent to: 相当于:
class MyThread extends Thread {
@Override
public void run() {
// do something
}
}
Thread t2 = new MyThread("Thread2");
So it is defining "stuff" about the new object in two ways: 因此,它通过两种方式定义有关新对象的“内容”:
A lambda can be used as an anonymous subclass (of a class
) or implementation (of an interface
) if the type is a functional interface , for example Callable
: 如果类型是函数接口 (例如Callable
),则lambda可用作(一个class
)匿名子class
或(一个interface
)实现。
Callable<Foo> r = () -> doSomething();
But Thread
is not a functional interface -- it does not have exactly one abstract method -- so you can't do this for Thread
. 但是Thread
不是一个功能接口-它没有确切的一个抽象方法-因此您不能对Thread
做到这一点。
For the specific case you have, Thread
has a two argument constructor, so you don't need to create a subclass. 对于特定的情况, Thread
具有两个参数的构造函数,因此您无需创建子类。
Thread t1 = new Thread( () -> someMethod(), "Thread1");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.