method.invoke的简单理解

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_42292373/article/details/102469975

接口

package com.bwie.service;

public interface StartService {
    public void dance();
}

实现类

package com.bwie.service;
public class FanServiceImpl implements StartService {
    public void dance() {
        System.out.println("我要看明星跳舞");
    }
}

测试类

public class ProxyTest {
    public static void main(String[] args) throws Exception {
        Class<FanServiceImpl> fanServiceClass = FanServiceImpl.class;
        FanServiceImpl fanService = fanServiceClass.newInstance();
        Method method = fanServiceClass.getMethod("dance",null);

        /**
         * 知道了调用的method对象 以及 当前了类 fanservice,传入参数就行,
         * 加入此时dance方法他有参数 。此时   public void dance(String name);他有参数此时的
         *  method.invoke(fanService,任意的字符串); 这个方法就类似在反射
         * 中调用这个方法
         * 
         * 前提是知道这个类的实例,还有 method;
         */
        method.invoke(fanService,null);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_42292373/article/details/102469975