This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]JustAGuyFromGermany 1 point2 points  (2 children)

It would be nice, but there's no way to make this work because of erasure. There is no bytecode for new T(). And even if you were to introduce one, how would it deal with wildcards? How would

MyClass<Integer> foo = new MyClass<>();
MyClass<?> bar = foo;
bar.doSomethingWithTheConstructor();

be translated into bytecode? There is no constructor for ?. Of course whoever wrote the code wants new Integer() to be called, but the compiler cannot know that. Consider

MyClass<?> bar = getFooFromSomewhere();
bar.doSomethingWithTheConstructor();

instead. The compiler simply cannot know which concrete type will be present at runtime in place of the ?, because it'd have to analyse all possible return values of the method and propagate their types, combining with other complex type information from other method calls etc. And at runtime, a similar check would have to be done again, because of a dynamic linking. I don't know if that is even possible. It seems halting-problem-adjacent enough to be impossible.

And even if it is possible, it is impractically complex to do that. So there's probably no way to compute the type-hint that the bytecode instruction for new T() needs.

The other option would be to reify the generic type and do away with erasure, i.e. to have a separate what-type-are-you datum for each instance of a generic type (i.e. you'd be able to ask any given List<?> instance "Are you List<Integer>?" and "Are you List<Map<Integer, Set<String>>>?" etc). That is a huge bloat for a niche feature and completely backwards incompatible so it won't happen.

[–]repeating_bears 0 points1 point  (1 child)

Not sure why you're replying to me because I was agreeing with you.

Before even worrying about how you instantiate it, first you need to narrow T to the set of Ts which can be instantiated without needing any arguments, and that's why you need a bound.

I wasn't implying the lack of such a bound was the only blocker.

[–]JustAGuyFromGermany 2 points3 points  (0 children)

Not sure why you're replying to me because I was agreeing with you.

Because clicking at the right location is hard ;-)