【发布时间】:2015-11-20 11:25:47
【问题描述】:
我想创建一个从匿名类定义中获取对象的类来存储。我使用了一个泛型类型的类来实现这一点。然后我想使用功能接口定义一些操作,这些接口将这个对象作为参数来使用。
代码比文字更能说明问题。所以看看这个:
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”。但是我的第一种方法有什么问题?我真的不明白这里的问题。
【问题讨论】:
-
new Object(){ public String text = "Something"; })
标签: java generics lambda anonymous-class