gpt4 book ai didi

java - 如何在另一个方法之后调用一个方法?

转载 作者:行者123 更新时间:2023-12-02 02:10:15 25 4
gpt4 key购买 nike

假设我有以下代码:

Method myMethod = Entry.class.getDeclaredMethod("get" + criteria);
entries.get(index).getPort();

我想用反射方法“myMethod”替换 getPort 方法。如何在另一个方法之后调用反射方法? (在本例中为entries.get(index))

这可能是一个非常简单的问题,但我到处搜索并没有真正找到答案。

最佳答案

From the documentation:

Reflection provides a means for invoking methods on a class. Typically, this would only be necessary if it is not possible to cast an instance of the class to the desired type in non-reflective code. Methods are invoked with java.lang.reflect.Method.invoke(). The first argument is the object instance on which this particular method is to be invoked. (If the method is static, the first argument should be null.) Subsequent arguments are the method's parameters. If the underlying method throws an exception, it will be wrapped by an java.lang.reflect.InvocationTargetException. The method's original exception may be retrieved using the exception chaining mechanism's InvocationTargetException.getCause() method.

就您而言:

myMethod.invoke(entries.get(index), null);

关于java - 如何在另一个方法之后调用一个方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50123232/

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