Call private Method.


    class Program
    {
        static void Main(string[] args)
        {
            MethodInfo method = typeof(Calculate).GetMethod("add", BindingFlags.Public
                | BindingFlags.NonPublic | BindingFlags.Instance);
            if (method == null)
            {
                return;
            }
            object[] paras = { 10, 20 };
            object result = method.Invoke(new Calculate(), paras);
            Console.WriteLine(result);
            Console.ReadLine();
        }
    }
Call private Method.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
代码中的问题是: 1. 在调用callMethod()方法时,传入的参数类型不匹配,应该将数字1,2,3,4,5修改为1.0,2.0,3.0,4.0,5.0,即将整型转换为浮点型。对于字符串"3",应该将其改为字符'3'。 2. 在调用callMethod()方法时,获取方法的Method对象时,应该使用Double[].class和String[].class而不是Double.class和String.class,因为参数是可变的数组。 修改后的代码如下: ```java package com.enmo.mdi.distributedcomputing.distributed; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class Algorithm { public Algorithm() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { } private Double sum(Double... args) { Double num = 0.0; for (Double d: args){ num += d; } return num; } private String add(String... args) { StringBuilder str = new StringBuilder(); for (String s: args){ str.append(s); } return str.toString(); } public static Object callMethod(String name, Object... args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { Class<?> clazz = Class.forName("com.enmo.mdi.distributedcomputing.distributed.Algorithm"); // 获取方法的Method对象 Method method = clazz.getDeclaredMethod(name, Double[].class); method.setAccessible(true); // 调用该方法 return method.invoke(null, (Object) args); } public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { // sum Double result = (Double) callMethod("sum", 1.0, 2.0, 3.0, 4.0, 5.0); System.out.println(result); String result1 = (String) callMethod("add", "1", "2", "3"); System.out.println(result1); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值