Java generics of generics of

后端 未结 4 1929
被撕碎了的回忆
被撕碎了的回忆 2020-12-15 10:04

I have a generic class which represents a fragment of text. That fragment of text may have any of a number of different modes (different types of highlighting). Those mode

相关标签:
4条回答
  • 2020-12-15 10:19

    Without testing, I'd guess:

    public class TextFragment<E extends TextFragmentMode<E>> {
    

    Hmm, short test shows it doesn't seem to work either...

    0 讨论(0)
  • 2020-12-15 10:21

    TextFragment<E> needs to say two things about E.

    • It "extends" TextFragmentMode<E>.
    • In order to do that, you must also constrain it to extend Enum<E>.

    Because of Java inheritance wonkiness, you need to write that the other way around:

    public class TextFragment<E extends Enum<E> & TextFragmentMode<E>> {
    
    0 讨论(0)
  • 2020-12-15 10:28

    You need to introduce a new type that accounts for the bound of Enum

    public class TextFragment<T extends Enum<T>, E extends TextFragmentMode<T>> {
    
    0 讨论(0)
  • 2020-12-15 10:45

    The problem is that you're trying to make E extend TextFragmentMode and Enum, which aren't related types. What type E would satisfy both constraints?

    I suspect you want two type parameters, something like this:

    public class TextFragment<E extends Enum<E>, M extends TextFragmentMode<E>>
    

    Now you have each constraint expressed on a different type parameter, and they both make sense - you can definitely find an E which is an enum, and an M which is a TextFragmentMode<E>. However, it's pretty complicated...

    ... do you definitely need it to be this generic? What will you be doing with M in the class? Could you not just take a TextFragmentMode<E> as a constructor parameter (or whatever) and make it generic in one type parameter again?

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