黑马程序员技术交流社区
标题:
用反射给泛型集合加元素问题
[打印本页]
作者:
孙飞
时间:
2012-8-9 00:39
标题:
用反射给泛型集合加元素问题
本帖最后由 孙飞 于 2012-8-9 00:43 编辑
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
public class GenericTest {
public static void main(String[] args){
ArrayList<Integer> collection=new ArrayList<Integer>();
collection.add(3);
//collection.add("hello");
Method method=null;
try {
method=collection.getClass().getMethod("add", Object.class);//为什么这里把Object.class改成String.class就不能把字符串加入集合呢?我下面要传入的是字符串,为什么这里不能用它的字节码文件类型做参数
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
try {
method.invoke(collection, "hello");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
System.out.println(collection);
}
}
复制代码
作者:
余明辉
时间:
2012-8-9 01:14
你拿到collection的字节码的时候,就已经是规定了泛型是Integer的了,而你非要传个String.class进去的话,编译是不通过的,因为泛型会在编译的时候自动帮你检查类型
作者:
尹善波
时间:
2012-8-9 01:19
本帖最后由 尹善波 于 2012-8-10 17:41 编辑
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
public class GenericTest {
public static void main(String[] args){
ArrayList<Integer> collection=new ArrayList<Integer>();
collection.add(3);
//collection.add("hello");
Method method=null;
try {
method=collection.getClass().getMethod("add", Object.class
);//获得字节码对象后可以用它的getMethod方
// 法去获得该字节码对象所在类的一个公共的成员方法,但getMethod方法要传入的参数是
//方法名字和该方法本身应该传入的参数,集合的add方法本身传入的参数是一个泛型,说明可以接收任
//意类型的参数, 所以应该传入Object的字节码文件类型做为参数才行
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
try {
method.invoke(collection, "hello");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
System.out.println(collection);
}
}
//刚刚改好 希望能有用到
作者:
孙飞
时间:
2012-8-9 23:59
没办法啊,哎
作者:
尹善波
时间:
2012-8-10 17:42
加个油啊
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2