2013-03-29 14 views
9

Próbuję osiągnąć pewnego rodzaju odbicie w Java. mam:Jak uzyskać wartość zwracaną wywołanej metody?

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

Jak uzyskać wartość z nowym O() C().?

+0

Czy sprawdziłeś zwracaną wartość 'method.invoke (this, x);'? – Apurv

+0

tak, dzięki odpowiedzi poniżej – c4rrt3r

Odpowiedz

14

Umieszczenie manekina klasy w celach informacyjnych, można zmienić swój kod 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; 
    } 
} 

Wystarczy uruchomić tę klasę.

+0

Naprawiono. Otrzymuję wyjątek: "Wyjątek w wątku" główny "java.lang.RuntimeException: Niekompilowany kod źródłowy - nieobsługiwany wyjątek java.lang.Exception; musi zostać przechwycony lub zadeklarowany jako zgłoszony" – c4rrt3r

+0

Musisz obsłużyć wyjątek. Umieść kod wywołujący w bloku try-catch. –

+0

Teraz dostaję NoSuchMethodException – c4rrt3r

4

invoke() Metoda zwraca obiekt, który jest zwracany po wykonaniu tej metody! więc możesz spróbować ...

Double dd = (Double)method.invoke(this,x); 
double retunedVal = dd.doubleValue(); 
Powiązane problemy