首页 > 其他 > 详细

《黑马程序员》 数组的反射

时间:2014-03-12 09:54:27      阅读:409      评论:0      收藏:0      [点我收藏+]
public class ReflectArray {

	/**
	 * 数组的反射
	 *   Array:是专门操作数组的类:
	 *      我们使用它可以拿到数组的长度和数组中的值
	 *         Array.getLength();
	 *         Array.get();
	 */
	public static void main(String[] args) {
		//我们根据用户传递的数据进行打印
		//至于用户传递的数据是数组还是单个数据我们都可以进行打印
//		Object obj=null;
		String[] str=new String[]{"abc","def","hij","fcg"};
		printOf(str);  //{abc,def,hij,fcg]
     
		printOf(1225);
		printOf("www.baidu.com");
		/**
		 *  {abc,def,hij,fcg]
			1225
			www.baidu.com
		 */
	}

	private static void printOf(Object obj) {
		Class clazz=obj.getClass(); //先得到对象的字节码文件
		if(clazz.isArray()){  //判断字节码文件对象是否是一个数组类
			//如果是
			//先得到数组的长度
			int length=Array.getLength(obj);  //得到数组的长度
			System.out.print("{");
			for(int x=0;x<length;x++){
				Object obj2=Array.get(obj, x); ////得到数组中的值
				if(x<length-1){
				System.out.print(obj2+",");  
				}else
					System.out.println(obj2+"]");
			}
		}else
			System.out.println(obj); //如果不是直接打印出数据
		
	}

《黑马程序员》 数组的反射,布布扣,bubuko.com

《黑马程序员》 数组的反射

原文:http://blog.csdn.net/zhizguoz/article/details/21065885

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!