简体   繁体   English

Java lambda表达式是否有办法不引用封闭对象?

[英]Is there a way for Java lambda expression not to have reference to enclosing object?

When lambda expression is used Java actually creates an anonymous (non-static) class. 当使用lambda表达式时,Java实际上会创建一个匿名(非静态)类。 Non-static inner classes always contain references their enclosing objects. 非静态内部类始终包含其封闭对象的引用。

When this lambda expression is called from another library that may invoke lambda in a different process that invocation crashes with class not found exception because it cannot find enclosing object's class in another process. 当从另一个库中调用此lambda表达式时,该表达式可能在另一个进程中调用lambda,调用因未找到类异常而崩溃,因为它无法在另一个进程中找到封闭对象的类。

Consider this example: 考虑这个例子:

public class MyClass {
    public void doSomething() {
        remoteLambdaExecutor.executeLambda(value -> value.equals("test"));
    }
}

Java will create an anonymous inner class that implements certain functional interface and pass it as a parameter to executeLambda(). Java将创建一个匿名内部类,它实现某些功能接口并将其作为参数传递给executeLambda()。 Then remoteLambdaExecutor will take that anonymous class across the process to run remotely. 然后remoteLambdaExecutor将整个进程中的匿名类进行远程运行。 Remote process knows nothing about MyClass and will throw 远程进程对MyClass一无所知,会抛出

java.lang.ClassNotFoundException: MyClass

Because it needs MyClass for that enclosing object reference. 因为它需要MyClass用于封闭对象引用。

I can always use a static implementation of the functional interface expected by an API, but that defeats the purpose and doesn't utilize lambda functionality. 我总是可以使用API​​所期望的功能接口的静态实现,但这会破坏目的并且不会使用lambda功能。

Is there way to solve it using lambda expressions? 有没有办法用lambda表达式来解决它?

UPDATE: I cannot use static class either unless it's somehow exported to that other process. 更新:我不能使用静态类,除非它以某种方式导出到其他进程。

Your initial premise is wrong. 你最初的前提是错误的。 The JRE will not generate an anonymous inner class. JRE 不会生成匿名内部类。 It may generate a class, but if your lambda expression does not access this or a non- static member of the class, it will not keep a reference to the this instance. 它可能会生成一个类,但如果您的lambda表达式不访问this或该类的非static成员,则它不会保留this实例的引用。

However, this does not imply that the class itself is unnecessary. 但是,这并不意味着课程本身是不必要的。 Since the class hosts the code of the lambda expression, it will always be needed. 由于该类承载lambda表达式的代码 ,因此总是需要它。 In this regard, your solution of using a static nested class doesn't change anything about it, as then, it's the static nested class that is needed for the execution of the code. 在这方面,使用static嵌套类的解决方案不会改变它的任何内容,因为它是执行代码所需的static嵌套类。

There is no way to transfer an object to a remote execution facility without transferring the class that contains the code to execute (unless the class already exists at the remote site). 如果不传输包含要执行的代码的类,则无法将对象传输到远程执行工具(除非该类已存在于远程站点)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM