在循环中的替代方法

huangapple go评论94阅读模式
英文:

Alternative to try-catch in a loop

问题

我有一个Method对象的列表,我想使用用户提供的参数来执行这些对象,直到运行时我才知道参数的类型或值。

我想循环遍历方法数组,并使用invoke方法执行它们,直到其中一个方法成功执行而没有异常。这样做好吗?

Method[] methods = cls.getMethods();

for (Method method : methods) {
    try {
        method.invoke(obj, param1, param2);
        break;
    }
    catch (Exception e) {
        System.out.println(e);
    }
}

有人告诉我在流程控制中使用trycatch是不好的主意,但我不太清楚为什么。在像这样的情况下,我不确定替代方案是什么,因为我预期在正常执行中会因为用户提供参数而引发异常。

非常感谢您的帮助。

英文:

I have a list of Method objects that I want to execute using user supplied parameters which I don't know the type or value until runtime.

I want to loop through the methods array and execute them using the invoke method until one of the methods executes successfully without an exception. Is this a good way to do it?

        Method[] methods = cls.getMethods();

        for (Method method : methods) {
            try {
                method.invoke(obj, param1, param2);
                break;
            }
            catch(Exception e)
            {
                System.out.println(e);
            }
        }

I've been told that using try and catch for flow control is bad idea, but I'm not sure why. I'm also not sure what the alternative would be in a situation like this where I expect an exception to occur in the normal execution because the user supplies the parameters.

Any help is greatly appreciated.

答案1

得分: 2

在这种特殊情况下,为什么不尝试使用 getParametersType()。当参数类型与 param1 和 param2 的类型匹配时,您实际上可以执行 method.invoke(obj, param1, param2);

一般而言,这是一个不好的主意,因为您不知道一个函数有多么耗费资源。因此,在最终抛出异常之前,它可能会消耗大量的处理时间或 CPU 周期。

英文:

In this particular case , why don't you try getParametersType().
And when it parameter types matches the type of the param1 and param2 you can actually execute method.invoke(obj, param1, param2);

In general it is bad idea because you don't know how heavy a function is . So it might consume lot of processing time or cpu cycle before ultimately throwing exception.

huangapple
  • 本文由 发表于 2020年9月24日 01:34:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/64033380.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定