Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I list all methods of all imported classes in a file using Java?

Tags:

java

My objective is to look at some lines of codes of an external file and count the number of functions of a class are called then.

For example, if I have the following code:

import java.io.BufferedReader;
import whatever.MyClass;
import java.util.ArrayList;
...
...
public void example(){
    InputStreamReader isr = new InputStreamReader (whatever);
    MyClass object = new MyClass();
    someArrayList.add(whatever2)
    someArrayList.add(whatever3)
}

In this case, BufferedReader and MyClass functions were called once, and ArrayList functions were called twice.

My solution for that is get a list of all methods inside the used classes and try to match with some string of my code. For classes created in my project, I can do the following:

jar -tf jarPath

which returns me the list of classes inside a JAR . And doing:

javap -cp jarPath className

I can get a list of all methods inside a JAR whit a specific class name. However, what can I do to get a external methods names, like add(...) of an "external" class java.util.ArrayList? I can't access the .jar file of java.util.ArrayList correct? Anyone have another suggestion to reach the objective?

like image 205
Lucas Pace Avatar asked Sep 29 '21 20:09

Lucas Pace


People also ask

Can you name public methods that each Java class has?

The public methods include that are declared by the class or interface and also those that are inherited by the class or interface. Also, the getMethods() method returns a zero length array if the class or interface has no public methods or if a primitive type, array class or void is represented in the Class object.

Which Java classes are automatically imported?

For convenience, the Java compiler automatically imports two entire packages for each source file: (1) the java. lang package and (2) the current package (the package for the current file).

How do you call all classes in Java?

To call a method in Java, write the method name followed by a set of parentheses (), followed by a semicolon ( ; ). A class must have a matching filename ( Main and Main. java).

How to get all methods of a class in Java?

Given a class in java containing public,private & protected methods. Public methods. Protected methods. We will print all methods of Person class using class “ Class “ . We will use getDeclaredMethods () of Class to retrieve all methods.

How do I import classes in Java?

There is one other “shortcut” method of importing classes in Java, and that's by using a wildcard (*). Say for instance you just want to import ALL of the classes that belong in the java.util package, you could just use the code import java.util.*.

How to print all methods of class in Java ( example)?

Program: List all functions of class in java (example) System.out.println ("1. List of all methods of Person class"); System.out.printf ("%d. End - all methods of Person class", ++nMethod); 2. Output: print all methods of class in java (example) 1. List of all methods of Person class

What are Java imports?

Well, since you are already familiar with Java packages, Java imports flow naturally from packages. In Java, there are TONS of useful built in classes and methods that allow us to do things like: Okay, that's great, so what does that have to do with imports?


2 Answers

The compiler doesn't put the imports into the object file. It throws them away. Import is just a shorthand to the compiler.(Imports are a compile-time feature ).

first step :

use Qdox https://github.com/paul-hammant/qdox to get all the imports in a class :

String fileFullPath = "Your\\java\\ file \\full\\path";
JavaDocBuilder builder = new JavaDocBuilder();
builder.addSource(new FileReader( fileFullPath  ));

JavaSource src = builder.getSources()[0];
String[] imports = src.getImports();

for ( String imp : imports )
{
    System.out.println(imp);
}

second step : inspire from that code , loop through your imports (String array) and apply the same code and you will get the methods .

 import java.lang.reflect.Method;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;

  public class Tes {
  public static void main(String[] args) {
    Class c;
    try {
        c = Class.forName("java.util.ArrayList");
        Arrays.stream(getAccessibleMethods(c)).
                              forEach(System.out::println);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}

public static Method[] getAccessibleMethods(Class clazz) {
    List<Method> result = new ArrayList<Method>();
    while (clazz != null) {
        for (Method method : clazz.getDeclaredMethods()) {
            result.add(method);
        }
        clazz = clazz.getSuperclass();
    }
    return result.toArray(new Method[result.size()]);
}
}

Output :

  public void java.util.ArrayList.add(int,java.lang.Object)
  public boolean java.util.ArrayList.add(java.lang.Object)
  public boolean java.util.ArrayList.remove(java.lang.Object)
  public java.lang.Object java.util.ArrayList.remove(int)
  public java.lang.Object java.util.ArrayList.get(int)
  public java.lang.Object java.util.ArrayList.clone()
  public int java.util.ArrayList.indexOf(java.lang.Object)
  public void java.util.ArrayList.clear()
  .
  .
  .

All the code - one class :

  import java.io.FileNotFoundException;
  import java.io.FileReader;
  import java.lang.reflect.Method;
  import java.util.ArrayList;
  import java.util.Arrays;
  import java.util.List;

  import com.thoughtworks.qdox.JavaDocBuilder;
  import com.thoughtworks.qdox.model.JavaSource;

  public class Tester {
  public static void main(String[] args) {
  // put your .java file path
  // CyclicB is a class within another project in my pc
    String fileFullPath =
      "C:\\Users\\OUSSEMA\\Desktop\\dev\\OCP_Preparation\\src\\w\\CyclicB.java";
JavaDocBuilder builder = new JavaDocBuilder();
try {
    builder.addSource(new FileReader( fileFullPath  ));
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

JavaSource src = builder.getSources()[0];
String[] imports = src.getImports();

for ( String imp : imports )
{
    Class c;
    try {
        c = Class.forName(imp);
        Arrays.stream(getAccessibleMethods(c)).
                              forEach(System.out::println);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
 }
 }
  public static Method[] getAccessibleMethods(Class clazz) {
  List<Method> result = new ArrayList<Method>();
  while (clazz != null) {
    for (Method method : clazz.getDeclaredMethods()) {
        result.add(method);
    }
    clazz = clazz.getSuperclass();
  }
return result.toArray(new Method[result.size()]);
}
}

Output all the methods within the classes imported in the file CyclicB.java :

  private void java.lang.Throwable.printStackTrace(java.lang.Throwable$PrintStreamOrWriter)
  public void java.lang.Throwable.printStackTrace(java.io.PrintStream)
  public void java.lang.Throwable.printStackTrace()
  public void java.lang.Throwable.printStackTrace(java.io.PrintWriter)
  public synchronized java.lang.Throwable java.lang.Throwable.fillInStackTrace()
  .
  .
  .
like image 79
Oussama ZAGHDOUD Avatar answered Nov 13 '22 18:11

Oussama ZAGHDOUD


You can get accessible methods using getAccessibleMethods() method you just need to pass the class as a parameter

getAccessibleMethods(Test)

It will return array of methods

public static Method[] getAccessibleMethods(Class clazz) {
        List<Method> result = new ArrayList<Method>();
        while (clazz != null) {
            for (Method method : clazz.getDeclaredMethods()) {
                int modifiers = method.getModifiers();
                if (Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers)) {
                    result.add(method);
                }
            }
            clazz = clazz.getSuperclass();
        }
        return result.toArray(new Method[result.size()]);
    }
like image 25
Saurabh Dhage Avatar answered Nov 13 '22 18:11

Saurabh Dhage