我想创建一个类,该类可以从匿名类定义中获取对象并进行存储。我使用了一个通用类型的类来实现这一点。然后,我希望使用函数式接口定义一些操作,这些操作将获取此对象作为参数进行处理。
代码胜过言语。看看这个例子:
public class Test<T> {
@FunctionalInterface
public interface operation<T> {
void execute(T object);
}
private T obj;
public Test(T _obj){
obj = _obj;
}
public void runOperation(operation<T> op){
op.execute(obj);
}
public static void main(String[] args){
Test<?> t = new Test<>(new Object(){
public String text = "Something";
});
t.runOperation((o) -> {
System.out.println(o.text); // text cannot be resolved
});
}
}
我的问题是在函数式接口的实现中,o.text无法解析。这是某种类型擦除的后果吗?
有趣的是,当我在构造函数中实现函数式接口时,可以让这段代码正常工作。
请看下面的代码:
public class Test<T> {
@FunctionalInterface
public interface operation<T> {
void execute(T object);
}
private T obj;
private operation<T> op;
public Test(T _obj, operation<T> _op){
obj = _obj;
op = _op;
}
public void runOperation(){
op.execute(obj);
}
public static void main(String[] args){
Test<?> t = new Test<>(new Object(){
public String text = "Something";
}, (o) -> {
System.out.println(o.text);
});
t.runOperation();
}
}
这个代码完美运行并且输出了"Something"。但是我的第一种方法出了什么问题呢?我真的不明白这里的问题在哪里。