I have methods like this:
public File method1(){
method2()
}
public method2(){
do something..
and get method1 return type(in this case File)
}
How do I get it? i tried like this..
Throwable t = new Throwable();
StackTraceElement[] elements = t.getStackTrace();
and get all the methods for the elements. And after that, getReturnType, but it doesn’t work. I also tried
public File method1(){
method2(this.getClass());
}
public method2(Class<?> className){
//problem here
}
But here the problem is that i can’t compare two elements, the one on the stack and the one from classname.getMethods().
Is there any way that I can send method return type to a method2? I need this because of making some history-like log. I know it can be done with aspectJ but I have to do it somehow like this.
EDIT:
The main problem I have is that I can get stack output, and see the method who called my method2 – that’s one fragment I need! Also I need that method’s return type, but the stack doesnt hold that information. Now, I can get all the methods from the class where the “method who called method2” is. The list of those methods, hold everything, return type, input parameters.. but that’s a pretty big list, 63 methods. So I have to compare them somehow to find out which one is the one FROM STACK. I can’t comapre them using name, because some differ with return type, hashcode is different – that’s where I’m stuck.
Update
If you really need to do this from a stack trace (which I would strongly recommend avoiding), I don’t think you can. The stack trace can tell you the class and method names, but it doesn’t include the method’s argument types, and so if the method is overloaded you can’t tell which one called
method2.I recommend you revisit your design. If
method2needs to know the return type of the method that calls it, then the method in question should pass that information intomethod2. Attempting to gather that information from a runtime stack is not only inefficient, but it’s a design red flag.Example:
There we have three overloads of
method1. This is not a problem formethod2, because each of them tellsmethod2what its return type is — or more accurately, I hope, what it needsmethod2to create for it or whatever.Original answer
For the specific case you list (esp. toward the end of your question), you can do this:
File.classis theClassinstance for theFileclass.For the general case of finding the type of the return value of a method in a class, you can use the reflection API. Get the
Classinstance for the class containing the method viaClass.forName, look up the method on thatClassinstance usingClass#getMethod, then useMethod#getReturnTypeon thatMethodto find out the return type’s class.