黑马程序员技术交流社区

标题: 怎么得到数组中元素的类型 [打印本页]

作者: 秦驰    时间: 2011-7-17 10:01
标题: 怎么得到数组中元素的类型
怎么得到数组中元素的类型
作者: 匿名    时间: 2011-7-17 11:22
把这个数组里面的元素拿出来。getclass一下不就好了么~....[code]public class TestArrayType {

        public static void main(String[] args) {
                Object[] a ={1,2,3,4};
                System.out.println(a.getClass().getName());
                System.out.println(a[1].getClass().getName());
        }
}[/code]结果是
[Ljava.lang.Object;
java.lang.Integer
上面表示的是一个Object类型的数组
下面表示第一个元素是Integer对象
作者: 匿名    时间: 2011-7-17 11:27
public class ArrayTest {
        public static void main(String[] agrs) throws Exception {
                Object[] obj = new Object[] { "a", 1 ,1.3};
                int len = Array.getLength(obj);
                for (int i = 0; i < len; i++) {
                        System.out.println(Array.get(obj, i).getClass().getName());
                }
        }
}
反射,循环读出就OK了。晕菜,楼上的同学,居然比我快了几分钟....




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2