这两天在看JavaEE的书,看到Spring时,书上有一句代码挺有意思的,Being b1 = ctx.getBean("dog", Being.class); 显然,getBean返回值的类型由Being.class这个参数决定。我知道这个肯定是泛型实现的,但具体怎么写没写过,而且我只是看书,电脑上地没有Spring(想看看代码都没的看,汗~),只好自己尝试着写写,最后写了一个类似的。
- public class Hello {
- /**
- * @param args
- * @throws IOException
- * @throws NoSuchMethodException
- * @throws InvocationTargetException
- * @throws IllegalAccessException
- * @throws InstantiationException
- * @throws SecurityException
- * @throws IllegalArgumentException
- */
- public static void main(String[] args) throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException{
- Node node = new Node();
- Integer i1 = new Integer(1);
- Integer i2 = new Integer(2);
- Integer i3 = node.plus(i1, i2, Integer.class);
- System.out.println(i3);
- }
-
- }
- public class Node {
- public <T> T plus(T arg1, T arg2, Class<T> cls ) throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException{
- int i1 = (Integer)cls.getDeclaredMethod("intValue").invoke(arg1);
- int i2 = (Integer)cls.getDeclaredMethod("intValue").invoke(arg2);
- return cls.getConstructor(int.class).newInstance(i1 + i2);
- }
- }
本文转自 dogegg250 51CTO博客,原文链接:http://blog.51cto.com/jianshusoft/657806,如需转载请自行联系原作者