Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instance of T (generic type) in Java

Tags:

java

generics

In short: Why cannot I write the following code in Java?

public class Foo<T> {
    public void foo(Object bar) {
        if (bar instanceof T) {
            // todo
        }
    }
}

Yeah, I know, the generics is kinda hacked into Java. Generics wasn't there until Java 1.5, and the generic type is lost during runtime.

I also know, there are some patterns 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 isn't it automatically done by the compiler?

For each class, where any generic type is present, the compiler could automatically add one (or more, if I have more generic types) parameter for each constructor, and bind those values to private fields. And each time, I write bar instanceof T it could compile this as clazzOfGenericT.isInstance(bar).

Is there any reason, this is not implemented?

I'm not totally sure, this wouldn't break backwards compatibility* - but then, new JVM languages (like Scala, or Kotlin) why doesn't have this feature?

*: IMHO it could be done, without break any backwards compatibility.

like image 717
Nagy Vilmos Avatar asked Apr 12 '16 22:04

Nagy Vilmos


1 Answers

Proposals for features added to Java are slow-moving and there are higher-priority features. "They haven't gotten to it yet."

Generics wasn't there until Java 1.5, and the generic type is lost during runtime.

...

My question is, why isn't it automatically done by the compiler?

For each class, where any generic type is present, the compiler could automatically add one (or more, if I have more generic types) parameter for each constructor, and bind those values to private fields.

Well, now, here you're just asking why Java doesn't store generic type information for run-time. You're asking for reification. The answer is that Java's generics are implemented with erasure, which you already know.

Yes, reification is possible and other languages do it. Yes, maybe Java will do it someday too. Maybe they will do it in a way similar to what you've suggested. Or maybe not.

Something like this could eventually be addressed by Project Valhalla.

like image 197
Radiodef Avatar answered Nov 15 '22 03:11

Radiodef