0
Methods[] method =classname.getClass().getDeclaredMethods();
在上面的代码中,我想获得特定方法的值。假设上面的方法会返回一些getter和setter方法。我们可以得到任何getter方法的价值吗?我们可以通过使用Methods []提取任何getter方法的值吗?
Methods[] method =classname.getClass().getDeclaredMethods();
在上面的代码中,我想获得特定方法的值。假设上面的方法会返回一些getter和setter方法。我们可以得到任何getter方法的价值吗?我们可以通过使用Methods []提取任何getter方法的值吗?
就像PeterMmm说的那样,你可以在Method上使用invoke,传递你想要调用的对象以及方法需要的其他参数,因为get方法通常没有参数,你可以像这样的:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class MethodsTest {
public int getA() {
return 5;
}
public int getB() {
return 8;
}
public static void main(String[] args) {
MethodsTest obj = new MethodsTest();
Method[] methods = obj.getClass().getDeclaredMethods();
for (Method method: methods) {
if (method.getName().startsWith("get"))
try {
System.out.println(method.getName() + ": " + method.invoke(obj));
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
它将打印:
getB: 8
getA: 5
希望它有助于
您正在使用什么语言? –
您可[调用](https://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Method.html#invoke(java.lang.Object,%20java.lang.Object。 ..))方法并取回值。 – PeterMmm