如何获取调用方法的返回值? [英] How to get return value of invoked method?
本文介绍了如何获取调用方法的返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在 Java 中实现某种反射.我有:
I'm trying to achieve some sort of reflection in java. I have:
class P {
double t(double x) {
return x*x;
}
double f(String name, double x) {
Method method;
Class<?> enclosingClass = getClass().getEnclosingClass();
if (enclosingClass != null) {
method = enclosingClass.getDeclaredMethod(name, x);
try {
method.invoke(this, x);
} catch (Exception e) {
e.printStackTrace();
}
}
}
class o extends P {
double c() {
return f("t", 5);
}
}
我如何从 new o().c() 中获取价值?
How do I get value from new o().c()?
推荐答案
把虚拟类放给你参考,你可以相应地改变你的代码-
Putting the dummy class for your reference, you can change your code accordingly-
import java.lang.reflect.Method;
public class Dummy {
public static void main(String[] args) throws Exception {
System.out.println(new Dummy().f("t", 5));
}
double t(Double x) {
return x * x;
}
double f(String name, double x) throws Exception {
double d = -1;
Method method;
Class<?> enclosingClass = getClass();
if (enclosingClass != null) {
method = enclosingClass.getDeclaredMethod(name, Double.class);
try {
Object value = method.invoke(this, x);
d = (Double) value;
} catch (Exception e) {
e.printStackTrace();
}
}
return d;
}
}
只需运行这个类.
这篇关于如何获取调用方法的返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文