考虑我有以下代码:
class Foo {
Y func(X x) {...}
void doSomethingWithAFunc(Function<X,Y> f){...}
void hotFunction(){
doSomethingWithAFunc(this::func);
}
}
Run Code Online (Sandbox Code Playgroud)
假设hotFunction经常被调用.那么缓存是否可取this::func,也许是这样的:
class Foo {
Function<X,Y> f = this::func;
...
void hotFunction(){
doSomethingWithAFunc(f);
}
}
Run Code Online (Sandbox Code Playgroud)
就我对java方法引用的理解而言,虚拟机在使用方法引用时会创建匿名类的对象.因此,缓存引用将仅创建该对象一次,而第一种方法在每个函数调用上创建它.它是否正确?
是否应缓存出现在代码中热位置的方法引用,或者VM是否能够对此进行优化并使缓存变得多余?是否存在关于此的一般最佳实践,或者这种高度VM实现是否特定于此类缓存是否有用?
我对内部类和lambda表达有些困惑,我试着问一个问题,然后又出现了另一个疑问,并且可能更好地发布另一个问题,而不是评论前一个问题.
直截了当:我知道(谢谢Jon)这样的事情无法编译
public class Main {
public static void main(String[] args) {
One one = new One();
F f = new F(){ //1
public void foo(){one.bar();} //compilation error
};
one = new One();
}
}
class One { void bar() {} }
interface F { void foo(); }
Run Code Online (Sandbox Code Playgroud)
由于Java如何管理闭包,因为one不是[有效]最终等等.
但是,这怎么允许的呢?
public class Main {
public static void main(String[] args) {
One one = new One();
F f = one::bar; //2
one = …Run Code Online (Sandbox Code Playgroud) 我知道关于这个问题有很多问题,即使是最近的问题,但我仍然无法解决一件事。考虑以下功能接口:
@FunctionalInterface
interface PersonInterface {
String getName();
}
Run Code Online (Sandbox Code Playgroud)
而这个实现:
class Person implements PersonInterface {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Run Code Online (Sandbox Code Playgroud)
如果查看这些线程1和2,我希望输出以下代码"Bob",而不抛出a,NullPointerException因为据我了解,在创建我的Supplier时,它捕获了Person实例。
Person p = new Person("Bob");
Supplier<String> f = p::getName;
p = null;
System.out.println(f.get());
Run Code Online (Sandbox Code Playgroud)
并正确输出 "Bob"
现在我不明白的是为什么下面的代码也没有输出"Bob"?
Person p = new Person("Bob"); …Run Code Online (Sandbox Code Playgroud) NullPointerException当我使用方法引用绑定到dog后来分配null给变量的变量时,为什么代码没有抛出?
我正在使用Java 8。
import java.util.function.Function;
class Dog {
private int food = 10;
public int eat(int num) {
System.out.println("eat " + num);
this.food -= num;
return this.food;
}
}
public class MethodRefrenceDemo {
public static void main(String[] args) {
Dog dog = new Dog();
Function<Integer, Integer> function = dog::eat;
dog = null;
// I can still use the method reference
System.out.println("still have " + function.apply(2));
}
}
Run Code Online (Sandbox Code Playgroud)