package cn.itcast_03; import java.lang.reflect.Constructor; import java.lang.reflect.Method; public class Hour09_Reflect { public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub //获取字节码文件对象 Class c = Class.forName("cn.itcast_01.Person"); //获取自己以及父亲所有的公共方法 //Method[] methods = c.getMethods(); //获取自己的所有方法 // Method[] methods = c.getDeclaredMethods(); // for(Method method : methods) { // System.out.println(method); // } /* * Person p = new Person(); * p.show(); */ //创建对象 Constructor con = c.getConstructor(); Object obj = con.newInstance(); //获取单个方法 Method m1 = c.getMethod("show"); m1.invoke(obj); System.out.println("-------"); Method m2 = c.getMethod("method", String.class); m2.invoke(obj, "hello"); Method m3 = c.getMethod("getString", String.class,int.class); Object objString = m3.invoke(obj, "hello",100); System.out.println(objString); // String s = (String)m3.invoke(obj, "hello",100); // System.out.println(s); //获取私有 Method m4 = c.getDeclaredMethod("function"); m4.setAccessible(true); m4.invoke(obj); } }
原文地址:https://www.cnblogs.com/wuruichao/p/8419710.html
时间: 2024-10-16 17:08:57