gpt4 book ai didi

java - 如何解析由静态方法组成的字符串以便我们可以调用它?

转载 作者:行者123 更新时间:2023-12-01 09:56:37 30 4
gpt4 key购买 nike

我正在尝试编写一个函数,该函数接收一个字符串,该字符串由一个静态方法组成,并以字符串数组作为参数。

例如,假设我们有一个带有静态方法的类:

package com.stack.examples;

public class Example {

public static void testMethod() {
System.out.println("method executed");
}
}

现在,我们的函数将位于另一个类中,如下所示:

package com.stack.functions;

public class Functions {

public void parseCommand(String command) {
//TODO, this is where my doubts lie
//The given string is always composed of a sequence of Java identifiers
//separated by the character ’.’, representing the full qualified name of
//a Java method (package.class.method)
command.execute(); //Would this work? Perhaps reflection would be ideal

}
}

我的目标是解析在 parseCommand 中作为参数给出的字符串,以便

parseCommand("com.stack.examples.Example.testMethod()");

实际上使用给定的参数调用静态方法(在本例中,该方法只会打印出“消息已执行”)。

最佳答案

在寻找解决此问题的替代方案后,我发现reflection对我来说很有效:

要执行的静态方法:

package test;

public class Example {
public static void testMethod() {
System.out.println("method executed");
}
}

主类:

package test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Main {

public static void reflectVulnerableMethod(String str) throws ClassNotFoundException, NoSuchMethodException, SecurityException,
IllegalAccessException, IllegalArgumentException, InvocationTargetException {
String[] parts = str.split("\\.");

String forKlazz = "";
for (int i=0; i<parts.length -1; i++) {
if (i != 0){
forKlazz += '.' + parts[i];
}
else forKlazz += parts[i];
}
Class<?> klazz = Class.forName(forKlazz);
Method m = klazz.getMethod(parts[parts.length-1]);


m.invoke(null);


}

public static void main(String[] args) {
try {
reflectVulnerableMethod("test.Example.testMethod");
} catch (ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
}
}

关于java - 如何解析由静态方法组成的字符串以便我们可以调用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37162275/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com