黑马程序员技术交流社区
标题:
数组的反射示例
[打印本页]
作者:
syusikoku
时间:
2014-3-12 06:40
标题:
数组的反射示例
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); //如果不是直接打印出数据
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2