Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get return value of invoked method?

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

How do I get value from new o().c()?

like image 224
c4rrt3r Avatar asked Mar 29 '13 04:03

c4rrt3r


2 Answers

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.

like image 183
Sudhanshu Umalkar Avatar answered Oct 14 '22 22:10

Sudhanshu Umalkar


invoke() method returns the object which is returned after that method execution! so you can try...

Double dd = (Double)method.invoke(this,x);
double retunedVal = dd.doubleValue();
like image 25
Aditya Jain Avatar answered Oct 14 '22 22:10

Aditya Jain