有趣的泛型方法

 这两天在看JavaEE的书,看到Spring时,书上有一句代码挺有意思的,Being b1 = ctx.getBean("dog", Being.class); 显然,getBean返回值的类型由Being.class这个参数决定。我知道这个肯定是泛型实现的,但具体怎么写没写过,而且我只是看书,电脑上地没有Spring(想看看代码都没的看,汗~),只好自己尝试着写写,最后写了一个类似的。

 

 
 
  1. public class Hello { 
  2.  
  3.     /** 
  4.      * @param args 
  5.      * @throws IOException  
  6.      * @throws NoSuchMethodException  
  7.      * @throws InvocationTargetException  
  8.      * @throws IllegalAccessException  
  9.      * @throws InstantiationException  
  10.      * @throws SecurityException  
  11.      * @throws IllegalArgumentException  
  12.      */ 
  13.     public static void main(String[] args) throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException{ 
  14.         Node node = new Node(); 
  15.         Integer i1 = new Integer(1); 
  16.         Integer i2 = new Integer(2); 
  17.         Integer i3 = node.plus(i1, i2, Integer.class); 
  18.         System.out.println(i3); 
  19.          
  20.     } 
  21.  
 
 
  1. public class Node { 
  2.      
  3.     public <T> T plus(T arg1, T arg2, Class<T> cls ) throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException{ 
  4.         int i1 = (Integer)cls.getDeclaredMethod("intValue").invoke(arg1); 
  5.         int i2 = (Integer)cls.getDeclaredMethod("intValue").invoke(arg2); 
  6.         return cls.getConstructor(int.class).newInstance(i1 + i2); 
  7.     } 

 


本文转自 dogegg250 51CTO博客,原文链接:http://blog.51cto.com/jianshusoft/657806,如需转载请自行联系原作者

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值