Can we call a method by inferring a type ?
Hi,
Pardon my ignorance. Why doesn't type inference help in writing code like this ?
<code>
public class TypeInferredMethodCall {
private interface Base {
public void x();
}
private static class Derived implements Base {
public void x(){
}
}
static <T> List<T> getList(Class<? extends T> type) {
// T.x(); -> Error
return new ArrayList<T>();
}
public static void main(String[] args) {
List<Base> list2 = getList( Base.class );
}
}
</code>
Thanks,
Mohan
Do you mean that you can't write T.x()? That is completely normal: you couldn't write Derived.x() either. More importantly, here T is being erased to Object, so you couldn't do this either:
static <T> List<T> getList(Class<? extends T> type,T obj) {
T.x()
}
for that to work you would have to do this:
static <T extends Base> List<T> getList(Class<? extends T> type,T obj) {
T.x()
}
static <T extends Base> void call( Class<? extends T> type,T obj) {
obj.x();
}
This works but there is no way to call a method without knowing the static type. The proposal to introduce 'invokedynamic' seems to be the only way.