如何初始化(新建)一个方法 ,如何方法逆向调用对象

package fft.property.copy;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


//新建一个计算器的类

public class Calculator {
    
    
    
    public int add(Integer i,Integer j){
        return i+j;
    }
    
    public int subject(Integer i,Integer j){
        return i-j;
    }
    
    public int multiply(Integer i,Integer j){
        return i*j;
    }
    
    public int devide(Integer i,Integer j){
        return i/j;
    }
    
     public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {
         
            //利用反射,加载类
            Class clz = Class.forName("fft.property.copy.Calculator");

            System.out.println("clz="+clz);

            //获取类对应的对象

            Calculator  calculator = (Calculator) clz.newInstance();

          //获取对象对应地方方法

            Method   mt= clz.getMethod("add", new Class[]{Integer.class,Integer.class});
            System.out.println("mt="+mt);
            //逆向调用 方法调用对象
            System.out.println(mt.invoke(calculator, new Object[]{4,5}));
            
        }
    
    
    
}

发布了195 篇原创文章 · 获赞 52 · 访问量 31万+

猜你喜欢

转载自blog.csdn.net/hongweideng/article/details/53835888