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

后端 未结 7 473
清歌不尽
清歌不尽 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条回答
  •  -上瘾入骨i
    2021-01-11 19:40

    An alternative would be to just accept the fact that you have no control over the type hierarchy of String/Integer and create an interface to give a common type for the classes you do have control over

    public int reverse(int value) {
        return Integer.valueOf(new StringBuilder(value + "").reverse()
                .toString());
    }
    
    public String reverse(String value) {
        return new StringBuilder(value + "").reverse().toString();
    }
    
    public  T reverse(T value) {
        value.reverse();
        return value;
    }
    
    public interface Reversible {
        public void reverse();
    }
    

提交回复
热议问题