package com.yjf.esupplier.common.test;import java.lang.reflect.Constructor;import java.lang.reflect.Method;/** * @author shusheng * @description 通过反射获取成员方法并使用 * @Email shusheng@yiji.com * @date 2019/1/5 18:37 */public class ReflectDemo3 { public static void main(String[] args) throws Exception { // 获取字节码文件对象 Class c = Class.forName("com.yjf.esupplier.common.test.Person"); // 获取自己的包括父亲的公共方法 Method[] methods1 = c.getMethods(); for (Method method : methods1) { System.out.println(method); } System.out.println("-------------------------------"); // 获取自己的所有的方法 Method[] methods2 = c.getDeclaredMethods(); for (Method method : methods2) { System.out.println(method); } System.out.println("-------------------------------"); //通过无参构造方法拿到对象 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"); System.out.println("-------------------------------"); // 返回值是Object接收 Method m3 = c.getMethod("getString", String.class, int.class); Object objString = m3.invoke(obj, "hello", 100); String s = (String) m3.invoke(obj, "hello", 100); System.out.println(objString); System.out.println(s); System.out.println("-------------------------------"); // private void function() Method m4 = c.getDeclaredMethod("function"); m4.setAccessible(true); m4.invoke(obj); }}
package com.yjf.esupplier.common.test;/** * @author shusheng * @description * @Email shusheng@yiji.com * @date 2018/12/29 13:42 */public class Person { private String name; int age; public String address; public Person() { } private Person(String name) { this.name = name; } Person(String name, int age) { this.name = name; this.age = age; } public Person(String name, int age, String address) { this.name = name; this.age = age; this.address = address; } public void show() { System.out.println("show方法的输出"); } public void method(String s) { System.out.println("method方法的输出: " + s); } public String getString(String s, int i) { return s + "---" + i; } private void function() { System.out.println("function方法的输出"); } @Override public String toString() { return "Person [name=" + name + ", age=" + age + ", address=" + address + "]"; }}