Getting T.class despite Java's type-erasure

后端 未结 5 859
小鲜肉
小鲜肉 2020-11-30 11:24

I\'m trying to bind an interface to its implementation as read from a configuration file so that I can feed it to my IoC container. Here\'s roughly what I\'m trying to do:<

5条回答
  •  情深已故
    2020-11-30 11:41

    You can get the actual type arguments for a generic superclass of a class. This blog post explores the possibilities presented by this, including a nice little trick using trivial anonymous inner classes. To quote directly:

    It turns out that while the JVM will not track the actual type arguments for instances of a generic class, it does track the actual type arguments for subclasses of generic classes. In other words, while a new ArrayList() is really just a new ArrayList() at runtime, if a class extends ArrayList, then the JVM knows that String is the actual type argument for List's type parameter.

提交回复
热议问题