How to get return value of invoked method?

前端 未结 2 1775
傲寒
傲寒 2021-02-20 02:00

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) {
    Me         


        
2条回答
  •  北恋
    北恋 (楼主)
    2021-02-20 02:14

    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;
        }
    }
    

    Just run this class.

提交回复
热议问题