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

后端 未结 7 471
清歌不尽
清歌不尽 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:55

    Unfortunately java does not provide such functionality directly. However I can suggest you the following work around:

    Create parametrized class Mirror with private constructor and 3 static factory methods that create instance of Mirror with specific parameter:

    public class Mirror<T> {
        private T value
        private Mirror(T value) {
            this.value = value;
        }
    
        public static Mirror<Integer> integerMirror(Integer value) {
            return new Mirror(value);
        } 
    
        public static Mirror<String> stringMirror(String value) {
            return new Mirror(value);
        } 
    
        public static Mirror<MagicValue> magicMirror(MagicValue value) {
            return new Mirror(value);
        } 
    }
    

    EDIT Obviously you can (and probably should) separate the class Mirror from its creating, e.g. put the factory methods to separate class MirrorFactory. In this case the constructor should become package protected.

    If you want to support large yet limited number of classes you can implement only one generic factory method

        public static <T> Mirror<T> createMirror(T value) {
            checkTypeSupported(value);
            return new Mirror(value);
        } 
    

    Method checkTypeSupported(value); may use some kind of metadatat (e.g. properties, JSON etc file) to get supported types. In this case however you will not enjoy the compile time validation.

    Other solution is to require that all supported types extend certain base class or implement interface:

    public class Mirror<T extends MyInterface> {}
    

    But this solution seems does not match your requirements since you need Integer, String and MagicValue.

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