如何初始化(新建)一個方法 ,如何方法逆向調用對象

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}));
            
        }
    
    
    
}

發佈了198 篇原創文章 · 獲贊 52 · 訪問量 32萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章