黑马程序员技术交流社区

标题: 数组的反射示例 [打印本页]

作者: syusikoku    时间: 2014-3-12 06:40
标题: 数组的反射示例
  1. public class ReflectArray {

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

  15. printOf(1225);
  16. printOf("www.baidu.com");
  17. /**
  18. * {abc,def,hij,fcg]
  19. 1225
  20. www.baidu.com
  21. */
  22. }

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

  39. }
复制代码






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