Weckar E.
Weckar E.

Reputation: 777

Is it possible to somehow overcome type erasure in Java?

Here's the thing. We use a lot of Wicket Panels in our application, and for testing purposes they should ideally be generated generically. Part of this works, in theory: For every parameter type in a constructor I have only one possible argument to offer, so it is a matter of finding what these parameter types are - Reflection. Problem being: Type Erasure. Many of the constructors use multiple versions of the Model< > class as parameters with various different type parameters to it. Type Erasure means that as far as I can find I have no way to differentiate between these at runtime. So, in this situation, is there any way to overcome or circumvent type erasure?

Upvotes: 1

Views: 470

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533520

You have a problem long before you use reflection and if you fix this, you not longer need to worry.

As there is no way to tell the difference between Model<A> and Model<B> you cannot overload two methods or constructors with these types. Instead you need to create one method which takes a Model<C> where C is the super class/interface of A and B.

You can't do this

interface A extends C { }
interface B extends C { }

class MyClass {
    MyClass<Model<A> modelA) { }
    MyClass<Model<B> modelB) { }

This won't compile as they have the same signature after erasure so instead you can do

class MyClass {
    MyClass<Model<? extends C> model) { }

Not only does this compile but there is no ambiguity at runtime.

Upvotes: 4

Related Questions