You can use the following steps to find all class names that include the name of the target method in the Jar file.
- Get entries for the specified jar file.
- Check each JarEntry for names. If the name ends in .class. Then enter the class name.
- Use the name of the filled class to get all methods using reflection.
- Compare the name and name of the target method. If they are equal, type the method name and class name in the console.
Use the above steps, we can find all the class names in the jar file with the specified name of the target method.
I wrote the code and ran an example searching for the class name in jar ' commons-lang-2.4.jar ' with the name of the target method removeCauseMethodName .
And the following message is displayed in the console.
The [removeCauseMethodName] method is included in the class [org.apache.commons.lang.exception.ExceptionUtils]
From the message we can see the class name, which includes the name of the target method.
The code is as follows:
Note: before running the code, we need to add jar 'commons-lang-2.4.jar' to the build path.
import java.io.IOException; import java.lang.reflect.Method; import java.util.Enumeration; import java.util.jar.JarEntry; import java.util.jar.JarFile; public class SearchMetodInJarFile { private static final String CLASS_SUFFIX = ".class"; public static void main(String[] args) throws IOException, SecurityException, ClassNotFoundException { String targetMethodClass = "removeCauseMethodName"; new SearchMetodInJarFile().searchMethodName(new JarFile( "D:\\Develop\\workspace\\Test\\commons-lang-2.4.jar"), targetMethodClass); } public void searchMethodName(JarFile[] jarFiles, String targetMethodName) throws SecurityException, ClassNotFoundException { for (JarFile jarFile : jarFiles) { searchMethodName(jarFile, targetMethodName); } } public void searchMethodName(JarFile jarFile, String targetMethodName) throws SecurityException, ClassNotFoundException { Enumeration<JarEntry> entryEnum = jarFile.entries(); while (entryEnum.hasMoreElements()) { doSearchMethodName(entryEnum.nextElement(), targetMethodName); } } private void doSearchMethodName(JarEntry entry, String targetMethodName) throws SecurityException, ClassNotFoundException { String name = entry.getName(); if (name.endsWith(CLASS_SUFFIX)) { name = name.replaceAll("/", ".") .substring(0, name.lastIndexOf(".")); Method[] methods = Class.forName(name).getDeclaredMethods(); for (Method m : methods) { if (targetMethodName.equals(m.getName())) { System.out.println(String.format( "Method [%s] is included in Class [%s]", targetMethodName, name)); break; } } } } }
Hope this can help you.
source share