数组反射的应用

import java.lang.reflect.Array;

public class ReflectTest

{

        public static void main(String[] args)  

                {  

                          int[] a1=new int[]{1,2,3};  

                           /*  

                             * 给的是数组   

                             */  

                          printObject(a1);

                               /*  

                                * 给的不是数组   

                                */   

                           printObject("xcv");  

                  }  

           private static void printObject(Object obj)

                 {   

                          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);

                                               }

                        }

}

posted @ 2015-05-08 18:53  冰林  阅读(163)  评论(0编辑  收藏  举报