In short: why can't I write the following code in Java?
public class Foo<T> { public void foo(Object bar) { if (bar instanceof T) {
Yes, I know that generics are called in Java. There were no generators before Java 1.5, and the generic type was lost at runtime.
I also know that there are some templates for it. For example:
public class Foo<T> { Class<T> clazz; public Foo(Class<T> clazz) { this.clazz = clazz; } public void foo(Object bar) { if (clazz.isInstance(bar)) {
My question is: why is this not done automatically by the compiler?
For each class where there is some common type, the compiler can automatically add one (or more, if I have a more general type) parameter for each constructor and bind these values ββto private fields. And every time I write bar instanceof T , he could compile it as clazzOfGenericT.isInstance(bar) .
Is there any reason this is not implemented?
I'm not quite sure this will not violate compatibility * - but then new JVM languages ββ(for example, Scala or Kotlin) why this function does not have?
*: IMHO this can be done without interruptions in backward compatibility.
java generics
Nagy Vilmos
source share