public class ReflectPhone2 { public static void main(String[] args) throws Exception { //获取字节码文件 Class<?> rName = Class.forName(全限定类名); /** * 获取构造方法 * */ //获取___所有public的构造方法, //如果还要获取所有的构造方法用getDeclaredConstructors()方法 Constructor<?>[] constructors = rName.getConstructors(); //获取___指定的构造方法,这获取的是无参构造方法, //要获取有参的请在行参列表上写上(数据类型.class,数据类型.class); Constructor<?> constructor = rName.getConstructor(); //调用___无参构造方法 Object newInstance = constructor.newInstance(); /** * 获取方法 * */ //获取___类中所有的public修饰的方法,其中包括父类的方法。 //如果还要获取所有的方法用getDeclaredMethods()方法 Method[] methods = rName.getMethods(); //获取___指定的方法,这获取的是无参方法, //要获取有参的请在行参列表上写上(指定的方法名,数据类型1.class,数据类型2.class); Method method = rName.getMethod(方法名); //调用___非static修饰的方法需要invoke(对象,实参1,实参2), //有static修饰的方法需要invoke(null,实参1,实参2)。 //我这调用的非static修饰方法没有参数就只需一个对象 method.invoke(newInstance); /** * 获取字段 * */ //获取___类中的public字段。如果还要获取所有的字段用getDeclaredFields()方法 Field[] fields = rName.getFields(); //获取___指定的字段。 Field field = rName.getDeclaredField(指定的字段名); //设置___指定的字段,非static修饰,set(对象,值);有static修饰,set(null,值) field.set(newInstance,5.2); //调用___指定字段的值,非static修饰,get(对象);有static修饰,get(null) Object object = field.get(newInstance); System.out.println("指定字段的值=="+object); /** * 破坏包装declaredField.setAccessible(boolean)破坏封装,可以调用私有成员 * true:破环 * false:默认值,不破坏 */ Field field2 = rName.getDeclaredField(私有化的字段名); //破坏封装,不让字段私有化 field2.setAccessible(true); //设置字段的值 field2.set(newInstance,值); //调用设置后的字段值,并打印 Object object2 = field2.get(newInstance); System.out.println("破坏封装==="+object2); //获取全限定类名 String name = rName.getName(); System.out.println("全限定类名: "+name); //获取类名简写 String simpleName = rName.getSimpleName(); System.out.println("类名简写: "+simpleName); } }