I have the following classes:
public interface Entity {
}
public class EntityImpl implements Entity {
}
public interface Service<T extends Entity> {
T find(int id);
Optional<T> findOptional(int id);
}
public class ServiceImpl implements Service<EntityImpl> {
@Override
public EntityImpl find(int id) {
return new EntityImpl();
}
@Override
public Optional<EntityImpl> findOptional(int id) {
return Optional.of(new EntityImpl());
}
}
public class NewMain {
public static void main(String[] args) {
Service service = new ServiceImpl();
Entity e1 = service.find(1);
Optional<Entity> opt = service.findOptional(1);
Entity e2 = service.findOptional(1).get(); //compile error
}
}
I can get the correct Optional type without problems if saving the optional, but if I want to call a method on the returned generic Optional it seems the compiler is loosing the type bounds and I get just an Object. In the e2-line I get the following error from javac:
incompatible types: java.lang.Object cannot be converted to Entity
Why is it loosing the type information? How can I fix this problem?