反射获取方法对象API

137 阅读1分钟

image.png

image.png

package run;


import org.junit.Test;
import java.lang.reflect.Method;

public class FileDemo {
    @Test
    public void getMethods(){
        Class c = Account.class;
        Method[] methods = c.getMethods();//获取所有的方法对象(只能获取权限为public的方法)
    }
    @Test
    public void getDeclaredMethods(){
        Class c = Account.class;
        Method[] methods = c.getDeclaredMethods();//获取所有的方法对象(存在即可获取)
    }
    @Test
    public void getMethod() throws Exception {
        Class c = Account.class;
        Method method = c.getMethod("eat");//指定获取方法对象(只能获取权限为public的方法)(参数一:方法名 参数二:方法参数类类型)

    }
    @Test
    public void getDeclaredMethod() throws Exception {
        Class c = Account.class;
        Method method = c.getDeclaredMethod("run",String.class);//指定获取方法对象(存在即可获取)(参数一:方法名 参数二:方法参数类类型)

        method.setAccessible(true);//方法权限为private需要暴力反射,打开权限
        Object o =  method.invoke(new Account(),"狗子"); //唤醒方法(参数一:方法的类对象 参数二:方法形参(如果没有就不写))方法结果可以用Object接如果没有结果会返回null
        System.out.println(o);
    }