Java 如何使用字符串调用方法

Java 如何使用字符串调用方法,java,string,oop,Java,String,Oop,我正在尝试使用字符串来调用方法 假设我有一个名为Kyle的类,它有3个方法: public void Test(); public void Ronaldo(); public void MakeThis(); 我有一个字符串,带有我需要调用的方法的名称: String text = "Test()"; 现在我需要调用名称在该字符串中的方法: Kyle k = new Kyle(); k.text?您需要使用名为的东西。您需要使用java反射来实现这一点 见: 使用您的具体示例: Stri

我正在尝试使用字符串来调用方法

假设我有一个名为
Kyle
的类,它有3个方法:

public void Test();
public void Ronaldo();
public void MakeThis();
我有一个字符串,带有我需要调用的方法的名称:

String text = "Test()";
现在我需要调用名称在该字符串中的方法:

Kyle k = new Kyle();

k.text

您需要使用名为的东西。

您需要使用java
反射来实现这一点

见:

使用您的具体示例:

String text = "Test";
Kyle k = new Kyle();
Class clas = k.getClass();

// you'll need to handle exceptions from these methods, or throw them:
Method method = clas.getMethod(text, null);
method.invoke(k, null);
这没有
getMethod()
Method.invoke()
所需的异常处理,只涉及调用不带参数的方法的情况

另见:

尝试反射

import java.lang.reflect.Method;
class Kyle {
    public void Test(){System.out.println("invoking Test()");}
    public void Ronaldo(){System.out.println("invoking Ronaldo()");}
    public void MakeThis(){System.out.println("invoking MakeThis()");}

    public static void main(String[] args) throws Exception{
        Kyle k=new Kyle();
        String text = "Test";
        Class c=k.getClass();
        Method m=c.getDeclaredMethod(text);
        m.invoke(k);
    }
}
输出


调用Test()

反射是Java中一个有趣的特性。它允许基本的内省。这里使用
k.getClass().getMethod()

乙二醇

String text=“测试”;
Kyle k=新Kyle();
方法testMethod=k.getClass().getMethod(文本,新类[]{
/*在此处列出参数类,例如String.class、Kyle.class或留空表示无*/}
Object returnedValue=testMethod.invoke(k,新对象[]{
/*参数转到此处或为空表示无*/});

此答案的问题是链接已断开
String text = "Test";
Kyle k = new Kyle();
Method testMethod = k.getClass().getMethod(text, new Class<?>[] { 
    /*List parameter classes here eg. String.class , Kyle.class or leave empty for none*/} 
Object returnedValue = testMethod.invoke(k, new Object[] { 
    /* Parameters go here or empty for none*/});