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

后端 未结 7 472
清歌不尽
清歌不尽 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 {
        private T value
        private Mirror(T value) {
            this.value = value;
        }
    
        public static Mirror integerMirror(Integer value) {
            return new Mirror(value);
        } 
    
        public static Mirror stringMirror(String value) {
            return new Mirror(value);
        } 
    
        public static Mirror 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  Mirror 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 {}
    

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

提交回复
热议问题