Допустим, у меня есть следующий код:
Method myMethod = Entry.class.getDeclaredMethod("get" + criteria);
entries.get(index).getPort();
Я хочу заменить метод getPort отраженным методом myMethod. Как я могу вызвать отраженный метод после другого метода? (в данном случае entry.get (index))
Вероятно, это действительно простой вопрос, но я искал везде и не нашел ответа.
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);