package J20250806.reflection;

import java.lang.reflect.*;

/**
 * @author WanJl
 * @version 1.0
 * @title Demo11
 * @description
 * 案例4：方法调用
 *     在Calculator类中定义：
 *     公共方法add(int a, int b)返回两数之和
 *     私有方法multiply(double a, double b)返回两数之积
 *     使用反射调用这两个方法并输出结果。
 * @create 2025/8/6
 */
public class Demo11 {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        Class<Calculator> calculatorClass = Calculator.class;

        //获取构造方法，用来创建对象
        Constructor<Calculator> constructor = calculatorClass.getDeclaredConstructor();
        constructor.setAccessible(true);
        Calculator calculator = constructor.newInstance();

        //获取普通方法
        Method[] declaredMethods = calculatorClass.getDeclaredMethods();
        for (Method method:declaredMethods){
            method.setAccessible(true);
            Object invoke = method.invoke(calculator, 15, 66);
            System.out.println(invoke);
        }

        Method add = calculatorClass.getDeclaredMethod("add",int.class,int.class);
        add.setAccessible(true);
        System.out.println(add.invoke(calculator,15, 6));
        Method multiply = calculatorClass.getDeclaredMethod("multiply",double.class,double.class);
        multiply.setAccessible(true);
        System.out.println(multiply.invoke(calculator,15, 6));

    }
}
