简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM