Java generics - retrieve type

后端 未结 6 590
忘掉有多难
忘掉有多难 2020-12-18 04:18
public Interface Foo{...}

Is there a way to retrieve which T was given for an implementation of Foo?

For example,

6条回答
  •  一整个雨季
    2020-12-18 05:01

    EDIT

    Turns out for this case it is possible to get the generic information. Singleshot posted an answer which does just that. His should be the accepted answer. Re-qualifying mine.

    In general though, there are many cases where you are unable to get type information you might expect to be there. Java uses a technique called type erasure which removes the types from the generic at compile time. This prevents you from getting information about their actual binding at runtime in many scenarios.

    Nice FAQ on the subject:

    • http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html#Reflection

提交回复
热议问题