public static void main(String[] args) throws Exception{ //获取类的字节码的 3 种方式 DemoClass demoClass2=new DemoClass("hello3","hello4"); //获取DemoCalss类的字节码 Class clazz=DemoClass.class; //通过Class的静态方法来获取类的字节码 Class clazz2=Class.forName("com.itheima.DemoClass"); //通过对象获取其类的字节码 Class clazz3=demoClass2.getClass(); System.out.println("**********用反射实例化类的两种方式***********\r\n"); //用反射实例化类的两种方式 //Constructor constructor=clazz.getConstructor(null); //Object inst=constructor.newInstance(null) System.out.println("*******无参构造函数"); Object inst=clazz.newInstance();//直接使用无参构造函数 System.out.println("*******带参构造函数"); Constructor constructor=clazz.getConstructor(String.class,String.class); DemoClass demoClass3= (DemoClass) constructor.newInstance("hello1","hello2"); System.out.println("获取了 \t"+ demoClass3.strPublic); //用反射获取对象中的成员变量 2 种方式 Field field =clazz.getField("strPublic"); String strPublic=(String)field.get(demoClass2); System.out.println("反射获取了:\t"+strPublic); Field field2=clazz.getDeclaredField("strPrivate"); field2.setAccessible(true); String strPrivate=(String)field2.get(demoClass2); System.out.println("反射获取了私有成员函数:\t"+strPrivate); System.out.println("*********************"); Method method=clazz.getMethod("getPublicMethod", Integer.TYPE); //函数的调用方式,如果第一个参数为null表示是静态方法不需要对象 method.invoke(demoClass3, 4); } } class DemoClass{ public String strPublic="Public"; private String strPrivate="Private"; public DemoClass() { strPrivate+="初始化"; strPublic+="初始化"; System.out.println(strPublic+"\t"+strPrivate); } public DemoClass(String strPrivate,String strPublic){ this.strPrivate+="\t"+strPrivate; this.strPublic+="\t"+strPublic; System.out.println(strPublic+"\t"+strPrivate); } public void getPublicMethod(int i){ System.out.println("这是公有方法!"+strPrivate+"\t"+i); } }
|