I want to create a class that gets an object from anonymous class definition to store. I used a generic typed class to achieve that. Then i want to define some operations using functional interfaces that gets this object as a parameter to work with.
Code says more than words. So have a look at this:
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
});
}
}
My problem is that o.text in the implementation of the functional interface cannot be resolved. Is this some kind of type erasure consequence?
The interesting thing is that I can get this code working when I implement the functional interface in the constructor.
Have a look at this code:
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();
}
}
This works perfect and prints out "Something". But what is wrong with my first approach? I really don't get the problem here.