Instance T (generic type) in Java

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) { // todo } } } 

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)) { // todo } } } 

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.

+7
java generics
source share
1 answer

Suggestions for functions added in Java are slow, and there are higher priority functions. "They have not achieved this yet."

There were no generals before Java 1.5, and the generic type was lost at runtime.

...

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.

Well, now, here, you are simply asking why Java does not store typical type information for runtime. You are asking for reification. The answer is that Java generics are implemented using erasures that you already know.

Yes, oververness is possible, and other languages ​​do it. Yes, maybe Java will do it too. Perhaps they will do it as you expected. Or maybe not.

Something like this could eventually be solved by Project Valhalla .

+3
source share

All Articles