反射学习--对接收数组参数的成员方法进行反射

来源:互联网 发布:sql server企业管理器 编辑:程序博客网 时间:2024/06/02 06:03
public class ClassMain {
/**
*写个程序,能够根据用户提供的类名,去执行该类中的Main方法。
* @throws Exception 
*/
public static void main(String[] args) throws Exception {
Method mainmethod=Class.forName(args[0]).getMethod("main", String[].class);//用反射方法得到某类的main方法
//mainmethod.invoke(null, new String[]{"11","22"});//兼容1.4版本,把这个数组拆包,变成三个参数,所以报参数错误。
//mainmethod.invoke(null, new Object[]{new String[]{"11","22"}});//把数组封装到Object数组中,拆包后是一个字符串型的数组。
mainmethod.invoke(null, (Object)new String[]{"11","22"});//把字符串数组标示成一个Object对象,编译器就不会拆包了。
}

}


//数组的反射
int[] a1=new int[3];
int[] a2=new int[4];
int[][] a3=new int[1][2];
String[] a4=new String[3];
System.out.println(a1.getClass()==a2.getClass());//返回true
// System.out.println(a1.getClass()== a3.getClass());//编译器提示错误
// System.out.println(a1.getClass()==a4.getClass());//编译器提示错误
System.out.println(a1.getClass().getSuperclass().getName());//得到数组的父类字节码名称java.lang.Object
                      
Object obj1=a1;
//Object[] obj2=a1;//一维基本类型的数组不能转换成Object类型数组,因基本类型不是Object对象。

0 0
原创粉丝点击