public class Test { public static void main(String[] args) { System.out.println(new DEF<>().bbb(2)); System.out.println(new DEF<>().bbb("2")); System.out.println(new DEF<>().bbb('2')); } } class DEF<T> { public T bbb(T c) { return new ABC<T>().aaa(c); } } class ABC<T> { @SuppressWarnings("unchecked") public T aaa(T a) { if (a instanceof String) { return (T) ((String) a).concat("1"); } else if (a instanceof Integer) { return (T) Integer.valueOf((((Integer) a) + 1)); } return a; } }
也可以使用泛型方法:
public class Test { public static void main(String[] args) { System.out.println(new DEF().bbb(2)); System.out.println(new DEF().bbb("2")); System.out.println(new DEF().bbb('2')); } } class DEF { public <T> T bbb(T c) { return new ABC<T>().aaa(c); } } class ABC<T> { @SuppressWarnings("unchecked") public T aaa(T a) { if (a instanceof String) { return (T) ((String) a).concat("1"); } else if (a instanceof Integer) { return (T) Integer.valueOf((((Integer) a) + 1)); } return a; } }
沒有留言:
張貼留言