简体   繁体   English

如何在 Java 中按名称(字符串)调用方法?

[英]How to call a method by name (String) in Java?

A<\/code>每个实例都有一个类B<\/code>的实例。 A<\/code>应该根据其成员变量method_num<\/code>在B<\/code>调用不同的方法。这是一个实现我想要的实现:

public class A {
    private B myB = new B();
    public int method_num = 1;
    public callBMethod() {
        if ( method_num == 1 )
            myB.method1();
        else
            myB.method2();
    }
}

public class B {
    public method1() { }
    public method2() { }
}

If you don't want to use reflection (and this is an excellent goal) then there are some neat features of enum s that allow you to set up an enum as a proxy.如果您不想使用反射(这是一个很好的目标),那么enum有一些简洁的功能可以让您将enum设置为代理。

public class A {
  private B myB = new B();
  public int method_num = 1;

  public void callBMethod() {
    // Could do it by name.
    BMethods.valueOf("method1").call(myB);
    // Or by number.
    BMethods.values()[method_num].call(myB);
  }

}

enum BMethods{
  method1 {
    @Override
    public void call(B b) {
      b.method1();
    }
  },
  method2 {
    @Override
    public void call(B b) {
      b.method2();
    }
  };

  public abstract void call (B b);
}

public class B {
  public void method1() {
  }

  public void method2() {
  }

}

You cannot.你不能。 Java doesn't treat functions as first class objects, because it doesn't have functional features like Python or C#. Java 不将函数视为第一类对象,因为它没有 Python 或 C# 之类的函数特性。

You can create a Command interface and pass that object reference:您可以创建一个 Command 接口并传递该对象引用:

public interface Command {
    void execute(Object [] args);
}

I think you can use reflection like this :我认为您可以像这样使用反射:

java.lang.reflect.Method method;
try {
  method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..);
} catch (SecurityException e) {
  // ...
} catch (NoSuchMethodException e) {
  // ...
}  

try {
  method.invoke(obj, arg1, arg2,...);
} catch (IllegalArgumentException e) {  //do proper handling
} catch (IllegalAccessException e) {//do proper handling
} catch (InvocationTargetException e) {//do proper handling

Maybe with Runnable objects ?也许与Runnable对象? You can pass from B a runnable, and call .run() directly from A您可以从 B 传递一个可运行文件,并直接从 A 调用.run()

Java reflection API provides you a way, where a Method type of object could be passed along with the target object and then the method could be invoked on the target object. Java 反射 API 为您提供了一种方法,可以将 Method 类型的对象与目标对象一起传递,然后可以在目标对象上调用该方法。

A sample example is here:示例如下:

Method m; // The method to be invoked

  Object target; // The object to invoke it on

  Object[] args; // The arguments to pass to the method

  // An empty array; used for methods with no arguments at all.
  static final Object[] nullargs = new Object[] {};

  /** This constructor creates a Command object for a no-arg method */
  public Command(Object target, Method m) {
    this(target, m, nullargs);
  }

  /**
   * This constructor creates a Command object for a method that takes the
   * specified array of arguments. Note that the parse() method provides
   * another way to create a Command object
   */
  public Command(Object target, Method m, Object[] args) {
    this.target = target;
    this.m = m;
    this.args = args;
  }

  /**
   * Invoke the Command by calling the method on its target, and passing the
   * arguments. See also actionPerformed() which does not throw the checked
   * exceptions that this method does.
   */
  public void invoke() throws IllegalAccessException,
      InvocationTargetException {
    m.invoke(target, args); // Use reflection to invoke the method
  }

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

相关问题 如何在Java中调用名称为字符串变量值的方法? - How to call a method whose name is the value of a string variable in java? 如何使用变量名调用Java方法? - how to call a java method using a variable name? 假设您只有类的字符串名称(以及方法名称/参数),那么如何从类中调用静态方法-在Java中 - How to call a static method from a class given that you only have the class's string name (and the method name / parameters) - in Java 在Java中,我想以“ foo”的名称调用对象上的方法,但是“ foo”是字符串。 我该如何解决? - In Java, I want to call a method on an object by the name of 'foo', but 'foo' is a string. How do I get around this? 如何调用存储在字符串变量中的 Java 方法 - How to call Java method that stored in string variable 如何在Java中获取方法的字符串名称? - How to get string name of a method in java? 如果 class 名称作为字符串传递,如何动态调用 class 的方法 - How to Dynamically call a method of a class if class name is passed as string Java-如何在不知道类名的情况下使用接口调用方法类 - Java - How to call method class with interface without know class name Java:如何从接口名称调用实现的方法 - Java:How to call Implemented method from interface name Java:如何使用类名直接调用方法 - Java: how it is possible to call method directly using class name
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM