Java:反射調(diào)用類的函數(shù)

1.若調(diào)用的函數(shù)所屬的類為自定義類,則將函數(shù)和類寫進(jìn)map中

Map methods = new HashMap();

methods.put("__plus","Param.tool");

2.通過將函數(shù)名稱獲取相應(yīng)的class,再獲取函數(shù)對象

Class c = Class.forName((String)methods.get(name.toString())); //通過函數(shù)名稱獲取對應(yīng)的類名,通過類名獲取類

Object obj = c.newInstance();

Method methods = c.getMethod(name.replace("__", ""), args.getClass()); //通過類對象獲取方法對象

3.調(diào)用函數(shù)

methods.invoke(obj, (Object)args);

注意:若傳遞的對象為數(shù)組時(shí),傳遞被認(rèn)為是多個參數(shù),導(dǎo)致wrong number of arguments異常

此處強(qiáng)制轉(zhuǎn)為一個Object對象即可

package Param;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

import java.util.HashMap;

import java.util.Map;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

import org.apache.jmeter.functions.BeanShell;

public class CallMethod {

private static Map methods = new HashMap();

public CallMethod() {

????methods.put("__plus","Param.tool");

}

public static Object getMethod(String method) throws ClassNotFoundException, NoSuchMethodException,

????SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

????Matcher m = Pattern.compile("(__[a-z]{1,})\\((.*?)\\)").matcher(method.toLowerCase());

????String name = "";

????String[] args = new String[] {};

????while(m.find()) {

????????System.out.println(m.group());

????????name = m.group(1);

????????args = m.group(2).split(",");

????}

????Class c = Class.forName((String)methods.get(name.toString()));

????Object obj = c.newInstance();

????Method methods =? c.getMethod(name.replace("__", ""), args.getClass());

????System.out.println(methods.toString());

????return methods.invoke(obj, (Object)args);

public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

CallMethod md = new CallMethod();

Object m = md.getMethod("__plus(1,2,3,4,5)");

System.out.println(m.toString());

}

}


相應(yīng)的加函數(shù)

package Param;

public class tool {

????public static String plus(String[] args) {

????????int sum =0;

????????for(int i=0;i<args.length;i++) {

????????????sum += new Integer(args[i]);

????????}

????????return "" + sum;

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容