gpt4 book ai didi

java - 调用从字符串方法创建并实现实际方法参数

转载 作者:行者123 更新时间:2023-11-30 05:06:24 25 4
gpt4 key购买 nike

我有一个关于 method.invoke() 的问题。我正在使用以下代码构造方法:

public void exec(String property_name, Object value){
try{
Method method = some_class.getClass().
getMethod("set"+property_name, new Class[] {
value.getClass()
}
);
method.invoke(some_class, value);
}catch(Exception e){
e.printStackTrace();
}
}

我的 some_class 有方法:

public void setA(Test test){
// do something
}

setA函数的参数是接口(interface),如下所示:

public interface Test{
public void write(String str);
}

当我将第一个示例代码中的 exec() 函数与 TestImpl(即 Test 的实现)一起使用时,会引发异常,通知在 some_class 中找不到该方法。但是,当我将函数 exec() 与原始类一起使用而不是扩展或实现时,方法 exec() 工作正常。

我应该怎么做才能使方法与类的实现一起使用?

使用 SSCCE 进行更新,以防某些人需要:

public class test {
public static void main(String[] args) {
exec("Name", new TestClassImpl());
}

public static void exec(String property_name, Object value){
try{
some_class sc = new some_class();
Method method = sc.getClass().
getMethod("set"+property_name, new Class[] {
value.getClass()
}
);
method.invoke(sc, value);
}catch(Exception e){
e.printStackTrace();
}
}
}

class some_class{
public some_class(){}
public void setName(TestClass test){
System.out.println(test.name());
}
}

interface TestClass{
public String name();
}

class TestClassImpl implements TestClass{
public String name() {
return "sscce";
}
}

提前致谢,谢尔希。

最佳答案

问题出在new Class[] { value.getClass() }。通过此方法,您可以搜索与参数类型具有完全相同的类的方法,但该方法不存在。

试试这个:

for (PropertyDescriptor prop : Introspector.getBeanInfo(some_class.getClass()).getPropertyDescriptors()) {
if (prop.getName().equals(property_name)) {
prop.getWriteMethod().invoke(some_class, value)
}
}

或者只使用Class.getMethods()并搜索setter名称和一个参数。

关于java - 调用从字符串方法创建并实现实际方法参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4963518/

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