简体   繁体   English

是否可以使用Integer动态调用方法和数组?

[英]Is it possible to use an Integer to call methods and arrays dynamically?

For example: 例如:

3 methods exist 存在3种方法

"map1method, “ map1方法,

map2method, map2方法,

map3mehtod" map3mehtod”

and I want to call the right one depending on what the integer 'activemap' has currently stored in it. 我想根据整数“ activemap”当前存储在其中的名称来调用正确的名称。

I could do an If statement 我可以做一个If语句

"If (activemap == 1) “如果(activemap == 1)

map1method; map1method;

elseif (activemap ==2) elseif(activemap == 2)

..." ...”

But is there a possible way of using the integer more efficiently? 但是,是否有可能更有效地使用整数?

Like a "map(activemap)method" 就像“地图(活动地图)方法”

Also could I also call a specific array in a batch of them in the same fashion. 我也可以用相同的方式在一批中调用特定的数组。

This is all in java by the way. 顺便说一下,这一切都在java中。

It is possible via reflection but I would urge you to stay away from that approach. 通过反思是可能的,但我敦促您不要采用这种方法。 Why not have all three methods built into one? 为什么不将这三种方法合而为一? One option would be to use a switch statement to handle the various cases: 一种选择是使用switch语句来处理各种情况:

void mapMethod(int activemap) {
    switch (activemap) {
    case 1:
        // map1method
        break;
    case 2:
        // map2method
        break;
    case 3:
        // map3method
        break;
     default:
        break;
    }
}

Now, you can call 现在,您可以致电

mapMethod(activemap)

If you want to take the reflection approach instead (which as I said I don't think you should), you can do something along the lines of 如果您想采用反射方法(正如我所说,我认为您不应该这样做),则可以按照

String methodName = "map" + activemap + "method";
MyClass.class.getDeclaredMethod(methodName).invoke(null);

A switch statement would be slightly easier to read: 使用switch语句会更容易阅读:

switch(activemap) {
   case 1:  map1method(); break;
   case 2:  map2method(); break;
}

You could use reflection to build the method name up at runtime, but that wouldn't be simpler. 您可以使用反射在运行时建立方法名称,但这并不简单。 Reflection is a lot of code. 反射是很多代码。

The most effective way to do this is to either create an enum to represent the different calls and use the int as a lookup for the enum value, or if that's not possible, to use a switch statement. 最有效的方法是创建一个enum来表示不同的调用,并使用int作为枚举值的查找,或者如果不可能,则使用switch语句。 You can use reflection to accomplish what you're talking about (look up a method at runtime based on its name), but it's less efficient and more cumbersome than either of those options. 您可以使用反射来完成您要谈论的内容(在运行时根据其名称查找方法),但是效率比这两个选项低,而且麻烦。

You can do it using Reflection , It will be something like this: 您可以使用Reflection来完成它,就像这样:

  java.lang.reflect.Method method;

  method = myObject.getClass().getMethod("map+"activemap"+method", param1.class, param2.class, ..);

  method.invoke(object, arg1, arg2,...);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM