public class MyGenericTest2<T >{
/** 求两个不确定类型的数值相加的泛型方法
* 通过使用泛型 两个数字相加 无论什么类型都可以
* @param t1
* @param t2
* @param <T>
* @author 1279938986@qq.com
*/
public <T extends Number> void sum(T t1,T t2){
if(t1.getClass()==Integer.class&&t2.getClass()==Integer.class){
System.out.print( t1.intValue() + t2.intValue());
}else if(t1.getClass()==Float.class&&t2.getClass()==Float.class){
System.out.print(t1.floatValue() + t2.floatValue());
}else if(t1.getClass()==Double.class&&t2.getClass()==Double.class){
System.out.print(t1.doubleValue() + t2.doubleValue());
} else if(t1.getClass()==Long.class&&t2.getClass()==Long.class){
System.out.print( t1.longValue() + t2.longValue());
}else if(t1.getClass()==Short.class&&t2.getClass()==Short.class){
System.out.print( t1.shortValue() + t2.shortValue());
}else if(t1.getClass()==Double.class||t2.getClass()==Double.class){
System.out.print(t1.doubleValue() + t2.doubleValue());
}else if(t1.getClass()==Long.class||t2.getClass()==Long.class){
System.out.print(t1.longValue() + t2.longValue());
} else if(t1.getClass()==Float.class||t2.getClass()==Float.class){
System.out.print(t1.floatValue() + t2.floatValue());
}else if(t1.getClass()==Integer.class||t2.getClass()==Integer.class){
System.out.print(t1.intValue() + t2.intValue());
}
}
public static void main(String[] args) {
MyGenericTest2<Number> my=new MyGenericTest2<>();
my.sum(10,2.5f);
}
}
//本代码参考https://blog.youkuaiyun.com/u014041033/article/details/50754475