数组反射

import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

public class ReflectTest {
 public static void main(String[] args) throws Exception {
  String str1="abc";
  
  Method methodCharAt=String.class.getMethod("charAt", int.class);
 // System.out.println(methodCharAt.invoke(str1,2));
  /*invoke 是方法对象methodCharAt上的方法,这个方法的作用是去调用
   * methodCharAt对应的方法*/
  
  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() == a4.getClass());
 // System.out.println(a1.getClass() == a3.getClass());
  System.out.println(a1.getClass().getName());
  System.out.println(a1.getClass().getSuperclass().getName());
  System.out.println(a4.getClass().getSuperclass().getName());
  
  Object aObj1 = a1;
  Object aObj2 = a4;
  //Object[] aObj3 = a1;
  Object[] aObj4 = a3;
  Object[] aObj5 = a4;
  
  System.out.println(a1);
  System.out.println(a4);
  System.out.println(Arrays.asList(a1));
  System.out.println(Arrays.asList(a4)); 
  
  */
  
  printObject(a1);
  printObject("dfhfghh");
 }

 private static void printObject(Object obj) {
  Class cla=obj.getClass();//得到参数的字节码
  if(cla.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);
    //不是数组则直接打印该对象
   }
  
 }
 }


    /*程序输出:
    1
    2
    3
    dfhfghh*/


 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值