Make a Java class generic, but only for two or three types

后端 未结 7 468
清歌不尽
清歌不尽 2021-01-11 19:17

(I was astonished not to be able to find this question already on stackoverflow, which I can only put down to poor googling on my part, by all means point out the duplicate.

7条回答
  •  孤街浪徒
    2021-01-11 19:37

    You can use so-called "witness" types to make the compiler do what you want.

    public interface Reversible< T > {
        public static final class IntReversible implements Reversible< Integer > {}
        public static final class StringReversible implements Reversible< String > {}
        public static final class MagicReversible implements Reversible< MagicValue > {}
    }
    
    public abstract class Mirror< T, R extends Reversible< T > > {
        // ...
    }
    
    public class IntMirror extends Mirror< Integer, IntReversible > {
        // ...
    }
    

    However, the reason your example doesn't make any sense is because you gain virtually nothing from using a generic in this context. What possible algorithm will reverse an integer or a string or a MagicValue without resorting to awful run-time type-checking and casting? The code will be all three reverse algorithms, wrapped with a hideous if-ladder.

提交回复
热议问题