I am planning to get list of methods defined in one package(CommonPackage) called by a class defined in another package (ServicePackage). For that, I need a to crawl a given method code and get the methods called outside of this class.
I have researched the Java reflections and was not able to find any solution for this. I also went through How to get the list of methods called from a method using reflection in C# and was not able to find any conclusive solution for JAVA specifically.
ClassA {
private ClassB classB;
public methodA1(){
classB.methodB1();
}
}
ClassB {
public methodB1(){
// Some code
}
}
Expected: For ClassA.MethodA1, we get the list of methods called inside it. Output: ClassB.MethodB1
In Java, a method can be invoked from another class based on its access modifier. For example, a method created with a public modifier can be called from inside as well as outside of a class/package. The protected method can be invoked from another class using inheritance.
public class YourClass{ private List<String> yourList; private List<String> add(){ List<String> strlist=new ArrayList<String>(); return strList; } public void methodOne(){ yourList=this. add(); } public void methodtwo(){ // here go with yourList variable. } }
You should make your variable arrayList part of the class as a field: public class Friends { List<MyObject> arrayList; public Friends(float x, float y) { arrayList = new ArrayList<MyObject>(); MyObject[] friendList = new MyObject[20]; } public void add() { for (int i = 0; i < 20; i++) { //arrayList. add(...). } } }
Reflection API provides visibility of class structure: its methods and fields. It does not allow however to look into methods.
What you need is to parse the byte code generated by compiler and extract interesting information from there. There are number of libraries that do this, e.g. Apache BCEL. You can take a look on similar question and relevant answer in SO.
I used an open source byte code manipulator called Javassists which already has an API to fetch method calls made in a given method. It also has method to fetch the code attribute which can give you the no of lines in a given method.
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.NotFoundException;
import javassist.expr.ExprEditor;
import javassist.expr.MethodCall;
public static void main(String[] args)
{
ClassPool cp = ClassPool.getDefault();
CtClass ctClass = null;
try {
ctClass = cp.get(className);
} catch (NotFoundException e) {
throw new RuntimeException(e);
}
CtMethod ctMethod = ctClass.getMethod(methodName);
ctMethod.instrument(
new ExprEditor() {
public void edit(MethodCall calledMethod) {
System.out.println("Method "+ calledMethod.getMethod().getName() + " is called inside "+methodName);
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With