1

如何检测 jar 文件中的类是否在扩展其他类,或者是否有对其他类对象的方法调用或创建了其他类对象?然后系统出哪个类扩展哪个类以及哪个类从哪个类调用方法。

我使用 Classparser 来解析 jar 。这是我的代码的一部分:

        String jarfile = "C:\\Users\\OOOO\\Desktop\\Sample.Jar";

        jar = new JarFile(jarfile);
        Enumeration<JarEntry> entries = jar.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            if (!entry.getName().endsWith(".class")) {
                continue;
            }

            ClassParser parser = new ClassParser(jarfile, entry.getName());
            JavaClass javaClass = parser.parse();
4

2 回答 2

3

有人投票以“太宽泛”来结束这个问题。我不确定这是否是适当的关闭原因,但它可能是,因为人们可以认为这个问题(这是对您之前的问题的后续)只是要求其他人为您做一些工作。

但是,要回答如何使用 BCEL 检测单个 JAR 文件中的类之间的引用的基本问题:

您可以JavaClassJarFile. 对于这些JavaClass对象中的每一个,您都可以检查这些Method对象及其InstructionList. 从这些说明中,您可以选择InvokeInstruction对象并进一步检查它们以找出实际调用哪个类的哪个方法。

下面的程序打开一个 JAR 文件(出于显而易见的原因,它是bcel-5.2.jar- 你无论如何都需要它......)并以上述方式处理它。对于每个JavaClassJAR 文件,它创建一个从所有引用JavaClass对象到Method在这些类上调用的 s 列表的映射,并相应地打印信息:

import java.io.IOException;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import org.apache.bcel.classfile.ClassFormatException;
import org.apache.bcel.classfile.ClassParser;
import org.apache.bcel.classfile.ConstantPool;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.InvokeInstruction;
import org.apache.bcel.generic.MethodGen;
import org.apache.bcel.generic.ObjectType;
import org.apache.bcel.generic.ReferenceType;
import org.apache.bcel.generic.Type;

public class BCELRelationships
{
    public static void main(String[] args) throws Exception
    {
        JarFile jarFile = null;
        try
        {
            String jarName = "bcel-5.2.jar";
            jarFile = new JarFile(jarName);
            findReferences(jarName, jarFile);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (jarFile != null)
            {
                try
                {
                    jarFile.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }

    private static void findReferences(String jarName, JarFile jarFile) 
        throws ClassFormatException, IOException, ClassNotFoundException
    {
        Map<String, JavaClass> javaClasses = 
            collectJavaClasses(jarName, jarFile);

        for (JavaClass javaClass : javaClasses.values())
        {
            System.out.println("Class "+javaClass.getClassName());
            Map<JavaClass, Set<Method>> references = 
                computeReferences(javaClass, javaClasses);
            for (Entry<JavaClass, Set<Method>> entry : references.entrySet())
            {
                JavaClass referencedJavaClass = entry.getKey();
                Set<Method> methods = entry.getValue();
                System.out.println(
                    "    is referencing class "+
                    referencedJavaClass.getClassName()+" by calling");
                for (Method method : methods)
                {
                    System.out.println(
                        "        "+method.getName()+" with arguments "+
                        Arrays.toString(method.getArgumentTypes()));
                }
            }
        }
    }

    private static Map<String, JavaClass> collectJavaClasses(
        String jarName, JarFile jarFile) 
            throws ClassFormatException, IOException
    {
        Map<String, JavaClass> javaClasses =
            new LinkedHashMap<String, JavaClass>();
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements())
        {
            JarEntry entry = entries.nextElement();
            if (!entry.getName().endsWith(".class"))
            {
                continue;
            }

            ClassParser parser = 
                new ClassParser(jarName, entry.getName());
            JavaClass javaClass = parser.parse();
            javaClasses.put(javaClass.getClassName(), javaClass);
        }
        return javaClasses;
    }

    public static Map<JavaClass, Set<Method>> computeReferences(
        JavaClass javaClass, Map<String, JavaClass> knownJavaClasses) 
            throws ClassNotFoundException
    {
        Map<JavaClass, Set<Method>> references = 
            new LinkedHashMap<JavaClass, Set<Method>>();
        ConstantPool cp = javaClass.getConstantPool();
        ConstantPoolGen cpg = new ConstantPoolGen(cp);
        for (Method m : javaClass.getMethods())
        {
            String fullClassName = javaClass.getClassName();
            String className = 
                fullClassName.substring(0, fullClassName.length()-6);
            MethodGen mg = new MethodGen(m, className, cpg);
            InstructionList il = mg.getInstructionList();
            if (il == null)
            {
                continue;
            }
            InstructionHandle[] ihs = il.getInstructionHandles();
            for(int i=0; i < ihs.length; i++) 
            {
                InstructionHandle ih = ihs[i];
                Instruction instruction = ih.getInstruction();
                if (!(instruction instanceof InvokeInstruction))
                {
                    continue;
                }
                InvokeInstruction ii = (InvokeInstruction)instruction;
                ReferenceType referenceType = ii.getReferenceType(cpg);
                if (!(referenceType instanceof ObjectType))
                {
                    continue;
                }

                ObjectType objectType = (ObjectType)referenceType;
                String referencedClassName = objectType.getClassName();
                JavaClass referencedJavaClass = 
                    knownJavaClasses.get(referencedClassName);
                if (referencedJavaClass == null)
                {
                    continue;
                }

                String methodName = ii.getMethodName(cpg);
                Type[] argumentTypes = ii.getArgumentTypes(cpg);
                Method method = 
                    findMethod(referencedJavaClass, methodName, argumentTypes);
                Set<Method> methods = references.get(referencedJavaClass);
                if (methods == null)
                {
                    methods = new LinkedHashSet<Method>();
                    references.put(referencedJavaClass, methods);
                }
                methods.add(method);
            }
        }
        return references;
    }

    private static Method findMethod(
        JavaClass javaClass, String methodName, Type argumentTypes[])
            throws ClassNotFoundException
    {
        for (Method method : javaClass.getMethods())
        {
            if (method.getName().equals(methodName))
            {
                if (Arrays.equals(argumentTypes, method.getArgumentTypes()))
                {
                    return method;
                }
            }
        }
        for (JavaClass superClass : javaClass.getSuperClasses())
        {
            Method method = findMethod(superClass, methodName, argumentTypes);
            if (method != null)
            {
                return method;
            }
        }
        return null;
    }
}

但是请注意,此信息可能并非在所有意义上都是完整的。例如,由于多态性,您可能并不总是检测到某个类的对象上调用了方法,因为它“隐藏”在多态抽象后面。例如,在类似的代码片段中

void call() {
    MyClass m = new MyClass();
    callToString(m);
}
void callToString(Object object) {
    object.toString();
}

调用toString实际上发生在MyClass. 但是由于多态性,它只能被识别为在“some Object”上调用这个方法。

于 2014-11-05T18:07:23.510 回答
1

免责声明:严格来说,这不是您问题的答案,因为它使用的不是BCEL而是Javassist。不过,您可能会发现我的经验和代码很有用。


几年前,我为此目的编写了 e Maven 插件(我称它为Storyteller Maven 插件) - 分析 JAR 文件中不必要或不需要的依赖项。

请看这个问题:

如何在 Maven 多项目中找到不必要的依赖项?

以及对此的回答。

尽管该插件有效,但当时我从未发布过它。现在我把它移到了 GitHub,只是为了让其他人可以访问它。

您询问解析 JAR 以分析.class文件中的代码。下面是几个 Javassist 代码片段。

在 JAR 文件中搜索类并为每个条目创建一个 CtClass

final JarFile artifactJarFile = new JarFile(artifactFile);
final Enumeration<JarEntry> jarEntries = artifactJarFile
        .entries();

while (jarEntries.hasMoreElements()) {
    final JarEntry jarEntry = jarEntries.nextElement();

    if (jarEntry.getName().endsWith(".class")) {
        InputStream is = null;
        CtClass ctClass = null;
        try {
            is = artifactJarFile.getInputStream(jarEntry);
            ctClass = classPool.makeClass(is);
        } catch (IOException ioex1) {
            throw new MojoExecutionException(
                    "Could not load class from JAR entry ["
                            + artifactFile.getAbsolutePath()
                            + "/" + jarEntry.getName() + "].");
        } finally {
            try {
                if (is != null)
                    is.close();
            } catch (IOException ignored) {
                // Ignore
            }
        }
        // ...
    }
}

找出引用的类就是

final Collection<String> referencedClassNames = ctClass.getRefClasses();

总的来说,我使用 Javassist 完成非常相似的任务的经验是非常积极的。我希望这有帮助。

于 2014-11-05T18:44:47.730 回答