Java Generic Class - Determine Type

前端 未结 8 2030
野性不改
野性不改 2020-11-27 12:48

If I am creating a java class to be generic, such as:

public class Foo

How can one determine internally to that class, what \'T\

相关标签:
8条回答
  • 2020-11-27 13:50

    Because of type erasure, there is no way to do this directly. What you could do, though, is pass a Class<T> into the constructor and hold onto it inside your class. Then you can check it against the three possible Class types that you allow.

    However, if there are only three possible types, you might want to consider refactoring into an enum instead.

    0 讨论(0)
  • 2020-11-27 13:51

    It looks like what you want is in fact not a Generic class, but an interface with a number of different implementations. But maybe it would become clearer if you stated your actual, concrete goal.

    0 讨论(0)
提交回复
热议问题