帮我怎么解决这个问题?


不懂的问题,先自己想想,多查看API 下面给你解释下这个程序,主要用到了反射机制: package com.test; import java.lang.reflect.*; public class ClassTest { public static void main(String[] args) { if (args.length != 1) { return; } else { try { //args不为空,传进来一个参数,比如com.test.Point (注意要加上包名) Class c = Class.forName(args[0]); //获取c所有的构造函数,这里就是获取到Point的构造函数。 Constructor[] cons = c.getDeclaredConstructors(); //获取c所有的方法 Method[] me = c.getDeclaredMethods(); //获取c所有的属性 Field[] fi = c.getDeclaredFields(); //获取第一个构造函数的参数类型,这里cl[0]为int,cl[1]也为int; Class[] cl = cons[0].getParameterTypes(); //定义一个Object数组 Object[] obj = new Object[cl.length]; { //下面是为构造函数创建参数 for (int i = 0; i < cl.length; i++) { //isPrimitive() 判断是否为基本类型。是则用包装类,不用担心,待会构造的时候虚拟机会自动拆包。 if (cl[i].isPrimitive()) { obj[i] = new Integer(i + 1); } } } //创建该构造方法的声明类的新实例,并用指定的初始化参数初始化该实例。o指向的是一个Point了 Object o = cons[0].newInstance(obj); //对带有指定参数的指定对象调用由此 Method 对象表示的底层方法。这里output没有参数,用null me[0].invoke(o, null); } catch (Exception e) { e.printStackTrace(); } } } } class Point { int x; int y; /* * static { System.out.println("Loading Point"); } */ void outPut() { System.out.println("x=" + x + "," + "y=" + y); } Point(int x, int y) { this.x = x; this.y = y; } }


本文链接:https://www.u1e.cn/xiehouyu/a/0e692e36edde83bd75fa5353 [复制]

猜你喜欢