Calling a method named “string” at runtime in Java

2019-01-11 21:27发布

问题:

How can we call a method which name is string at runtime. Can anyone show me how to do that in Java and C.

回答1:

In java it can be done through the reflection api.

Have a look at Class.getMethod(String methodName, Class... parameterTypes).

A complete example (of a non-static method with an argument) would be:

import java.lang.reflect.*;
public class Test {

    public String methodName(int i) {
        return "Hello World: " + i;
    }

    public static void main(String... args) throws Exception {
        Test t = new Test();
        Method m = Test.class.getMethod("methodName", int.class);
        String returnVal = (String) m.invoke(t, 5);
        System.out.println(returnVal);
    }
}

Which outputs:

Hello World: 5



回答2:

In Java you would use reflection:

Class<?> classContainingTheMethod = ...; // populate this!
Method stringMethod = classContainingTheMethod.getMethod("string");
Object returnValue = stringMethod.invoke(null);

This is a very simple case that assumes your method is static and takes no parameters. For non-static methods, you'd pass in the instance to invoke the method on, and in any case you can pass in any required parameters to the invoke() method call.



回答3:

Here is a base C example, I hope it will help you.

typedef void (*fun)(void);

static void hello()
{
  puts("hello world");
}

static void string()
{
  puts("string");
}

static void unknown()
{
  puts("unknown command");
}

struct cmd 
{
  char* name;
  void (*fun) (struct cmd* c);
};

static struct cmd commands[] = {
  { "hello", hello },
  { "string", string },
  { 0, unknown }
};


static void execute(const char* cmdname)
{
  struct cmd *c = commands;

  while (c->name && strcmp (cmdname, c->name))
    c++;
  (*c->fun) (c);
}

int main()
{
  execute("hello");
  execute("string");
  execute("qwerty");
}


回答4:

In Java:

If class A has a method "string()" then you call it by:

A a = new A();
a.string();

C does not have methods and you can't call them. You may be thinking of C++ which essentially has exactly the same syntax.



回答5:

In Java, you'll have to use the Java Reflection API to get a reference to the Method object representing your method, which you can then execute.



回答6:

In C (or C++) real reflection is not possible as it is a compiled language.

The most used is to have an associative container (a map) that can link a function name (as a string) to a function pointer. You have to fill in the map in the program with the value you want. This can't be done automatically.

You could also simply have a function that takes a string as parameter and then chose the right function to call with hand-made ifs.



回答7:

I'm quite sure you can put all your functions into the shared library and load them with dlopen + dlsym.