本帖最后由 李文富 于 2012-6-7 18:58 编辑
数组反射是遇到的问题,向大家请教
import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Arrays; public class ReflectTest { /** * @param args * @throws ClassNotFoundException * @throws SecurityException * @throws NoSuchMethodException */ public static void main(String[] args) throws Exception { int[] a1 = new int[]{1,2,3}; int[] a2 = new int[4]; int[][] a3 = new int[2][3]; String [] a4 = new String[]{"a","b","c"}; System.out.println(a1.getClass() == a2.getClass()); //System.out.println(a1.getClass() == a3.getClass());此处在eclipese中直接报错 ;张老师说过比较Class可以直接使用 == ,而为什么该处不可???? System.out.println(a1.getClass().equals(a4.getClass())); System.out.println(a1.getClass().equals(a3.getClass())); System.out.println(a1.getClass().getName()); System.out.println(a1.getClass().getSuperclass().getName()); System.out.println(a1.getClass().getSuperclass().getName()); Object aObj1 = a1; Object aObj2 = a4; //Object[] aObj3 = a1; Object[] aObj4 = a3; Object[] aObj5 = a4; System.out.println(a1);//打印出来的都是hashcode; System.out.println(a3);//打印出来的都是hashcode; System.out.println(a4);//打印出来的都是hashcode; System.out.println(Arrays.asList(a1));//打印仍然是hashcode System.out.println(Arrays.asList(a4));//字符串可以打印 Object obj = a4; printObject(obj); printObject(a1); //不能获取整个数组的元素类型;但可以得到某个元素的类型; a[0].getClass().getName(); } private static void printObject(Object obj) { // TODO Auto-generated method stub Class clazz = obj.getClass(); if(clazz.isArray()){ int len = Array.getLength(obj); for(int i=0; i<len; i++){ System.out.println(Array.get(obj,i)); } }else{ System.out.println(obj); } } }
|