本帖最后由 Kevin.Kang 于 2015-8-11 17:42 编辑
获取无参无返回值方法,并调用
- package com.kxg_02;
- import java.lang.reflect.Constructor;
- import java.lang.reflect.Method;
- public class MethodDemo {
- public static void main(String[] args) throws Exception {
- Class c = Class.forName("com.kxg_01.Person");
- // public Method[] getMethods():获取除了私有修饰的所有方法,包括从父类继承过来的
- Method[] methods = c.getMethods();
- for (Method m : methods) {
- System.out.println(m);
- }
- System.out.println("-----------------------");
- // public Method getMethod(String name,Class<?>... parameterTypes)
- // 第一个参数是方法名,第二个参数是该方法参数的class类型,没有就不写,或者写null
- Method m = c.getMethod("show", null);
- // public Object invoke(Object obj,Object... args)
- // 第一个参数是要调用方法的对象,第二个参数是该方法的实际参数,没有就不写,或者写null
- // 创建对象
- Constructor con = c.getConstructor();
- Object obj = con.newInstance();
- // 调用方法
- m.invoke(obj, null);
- }
- }
复制代码
有参无返和有参有返案例
- package com.kxg_02;
- import java.lang.reflect.Constructor;
- import java.lang.reflect.Method;
- public class MethodDemo2 {
- public static void main(String[] args) throws Exception {
- // 获取字节码文件对象
- Class c = Class.forName("com.kxg_01.Person");
- // 创建无参对象
- Constructor con = c.getConstructor();
- Object obj = con.newInstance();
- // 获取有参无返回值方法
- Method m = c.getMethod("show2", String.class);
- // 获取有参有返回值方法
- Method m2 = c.getMethod("show3", String.class);
- // 调用方法
- m.invoke(obj, "中国");
- String s = (String) m2.invoke(obj, "河南");
- System.out.println(s);
- }
- }
复制代码
|