Search code examples
javamethodsreflectionlocal-variables

how to get local variables of a method from another class


I have two classes A and B A class contains a method which has some of the local variables. now I want to fetch a particular variable's data type in the B class. can you please help me with this.

I researched about java reflection. but I found that I can not achieve this by using reflection, as local variables are stored in stack at the runtime. And reflection can only fetch instance or class variables.

for example,

class A{
     method1(){
         variable1;
     }
}
class B{
      method 2(){
           fetch variable1;
       }
}

I want the data type of variable1 as a result.

Is there any way to achieve it using mocking or something?


Solution

  • thanks for your support. I found the answer myself. I can do this via Java Regex Concept. As I know a little about the variable's naming pattern, So I am planning to parse the class1.java file and first will try pattern matching the method name and then the variables name. So that I will get the line on which the variable is declared. for example, if my variable is object, String abc=new String();

    I will try regex like, String regex=".=new.().*"

    So this will fulfill my purpose. Thanks again for helping.