4

对于我的检测工具,我想提供一个包装类加载器,用于在检测特定类后启动主方法。我的 ClassLoader 应该加载某些类的检测版本。但是对于 Jetty 和 JUnit,这种方法受到严重限制,因为它们构建了自己的类加载层次结构。

我不想传递 VM 参数,所以我无法更改 SystemClassLoader。ClassLoader.defineClass(String, byte[], int, int)但是我可以通过使用反射公开来强制使用我的课程。

ClassLoader scl = ClassLoader.getSystemClassLoader();
Method defineClass = ClassLoader.class.getDeclaredMethod(
        "defineClass", String.class, byte[].class, int.class, int.class);
defineClass.setAccessible(true);
for (String binaryName : classNamesToLoad) {
    byte[] bytecode = this.declaredClasses.get(binaryName);
    defineClass.invoke(scl, binaryName, bytecode, 0, bytecode.length);
}
defineClass.setAccessible(false);

这很好——但还有一个问题:如果我的一些类继承自或包含其他类,它们必须以正确的顺序加载,因为 SystemClassLoader 加载当前依赖的所有类——并且会加载未检测的版本.

这是一个示例,其中包含一些(命名不佳的)类以及它们必须加载的顺序:

A
A.A extends B.A
B
B.A extends B.C
B.C

必须按顺序加载

B
B.C
B.A
A
A.A

如果我只想加载检测版本。

有没有简单的方法——例如我还没有发现的“setSystemClassLoader”方法?

我不需要操作 SystemClassLoader 的解决方法?

还是我真的必须从我想要加载的类开始进行完整的传递依赖分析以确定正确的顺序(在这种情况下:有没有我可以使用的“现有技术”)?

谢谢!

4

2 回答 2

1

看起来没有办法绕过传递依赖分析。

我以这种方式解决了它,我真的希望有人能从这个实现中受益:

import java.io.IOException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.tree.ClassNode;

public class DependencyDetector {

    private static class Node implements Comparable<Node> {
        private final String binaryName;
        private final Node[] imports;
        private final int score;

        private Node(String binaryName, Node...imports) {
            this.binaryName = binaryName;
            this.imports = imports;
            this.score = calculateScore(imports);
        }

        public int compareTo(Node o) {
            return score - o.score;
        }

        private int calculateScore(Node...imports) {
            int newScore = 0;
            for (Node n : imports) {
                if (n.score >= newScore) {
                    newScore = n.score + 1;
                }
            }
            return newScore;
        }
    }

    private Map<String, Node> nodes = new HashMap<String, Node>();

    public DependencyDetector add(ClassNode node) {
        Node n = nodes.get(node.name);
        if (n == null) {
            n = createNode(node);
        }
        return this;
    }

    private Node createNode(ClassNode node) {
        String binaryName = node.name;
        String[] importNames = extractImportedBinaryNames(node);
        Node[] imports = new Node[importNames.length];
        for (int i = 0; i < imports.length; i++) {
            String importName = importNames[i];
            Node imp = nodes.get(importName);
            if (imp == null) {
                ClassNode cn = new ClassNode();
                String path = importName.replace('.', '/') + ".class";
                try {
                    new ClassReader(
                            ClassLoader.getSystemResourceAsStream(path)
                        ).accept(cn, ClassReader.SKIP_CODE);
                } catch (IOException e) {
                    throw new RuntimeException(
                        "could not read class " + importName);
                }
                imp = createNode(cn);
                nodes.put(importName, imp);
            }
            imports[i] = imp;
        }
        Node result = new Node(binaryName, imports);
        nodes.put(binaryName, result);
        return result;
    }

    private String[] extractImportedBinaryNames(ClassNode node) {
        String binaryName = node.name;
        ArrayList<String> nodesToAdd = new ArrayList<String>();
        int endOfOuter = binaryName.lastIndexOf('$');
        if (endOfOuter >= 0) {
            nodesToAdd.add(binaryName.substring(0, endOfOuter));
        }
        if (node.superName != null) {
            nodesToAdd.add(node.superName);
        }
        if (node.interfaces != null) {
            for (String interf : (List<String>) node.interfaces) {
                if (interf != null) {
                    nodesToAdd.add(interf);
                }
            }
        }
        return nodesToAdd.toArray(new String[nodesToAdd.size()]);
    }

    public String[] getClassesToLoad(String...binaryNames) {
        String[] classNames = binaryNames != null && binaryNames.length > 0
                ? binaryNames.clone()
                : nodes.keySet().toArray(new String[nodes.size()]);
        ArrayDeque<Node> dependencyQueue = new ArrayDeque<Node>();
        for (String className : classNames) {
            Node node = nodes.get(className.replace('.', '/'));
            dependencyQueue.add(node);
            if (node == null) {
                throw new RuntimeException(
                    "Class " + className + " was not registered");
            }
        }
        HashMap<String, Node> dependencyMap = new HashMap<String, Node>();
        while (!dependencyQueue.isEmpty()) {
            Node node = dependencyQueue.removeFirst();
            dependencyMap.put(node.binaryName, node);
            for (Node i : node.imports) {
                dependencyQueue.addLast(i);
            }
        }
        ArrayList<Node> usedNodes =
            new ArrayList<Node>(dependencyMap.values());
        Collections.sort(usedNodes);
        String[] result = new String[usedNodes.size()];
        int i = 0;
        for (Node n : usedNodes) {
            result[i++] = n.binaryName.replace('/', '.');
        }
        return result;
    }

    public boolean contains(String binaryName) {
        return nodes.containsKey(binaryName.replace('.', '/'));
    }
}

它的用法是这样的:在 a 上DependencyDetector,您调用add(ClassNode)以添加 aClassNode及其所有依赖项(它扩展或实现或包含的所有类)。完成构建依赖关系树后,调用以按必要顺序getClassesToLoad()检索所有依赖关系作为包含二进制名称的 a。String[]您还可以通过将二进制名称指定为getClassesToLoad(...).

现在,当我检测类时,我还添加了ClassNode并且DependencyDetector可以检索我需要将其传递给这样的方法的所有内容:

/**
 * load the specified classes (or all instrumented classes)
 * and all their dependencies with the specified ClassLoader.
 * @param loader
 * @param binaryNames binary names of all classes you want to load
 *        - none loads all instrumented classes
 */
public void loadIntoClassLoader(ClassLoader loader, String...binaryNames) {
    final String[] classNamesToLoad =
        dependencies.getClassesToLoad(binaryNames);
    Method defineClass = null;
    Method findLoadedClass = null;
    try {
        // crack ClassLoader wide open and force-feed it with our classes
        defineClass = ClassLoader.class.getDeclaredMethod(
                "defineClass", String.class, byte[].class,
                int.class, int.class);
        defineClass.setAccessible(true);
        findLoadedClass = ClassLoader.class.getDeclaredMethod(
                "findLoadedClass", String.class);
        findLoadedClass.setAccessible(true);
        for (String binaryName : classNamesToLoad) {
            if (!binaryName.startsWith("java.")) {
                if (findLoadedClass.invoke(loader, binaryName) == null) {
                    byte[] bytecode = getBytecode(binaryName);
                    defineClass.invoke(loader, binaryName, bytecode,
                        0, bytecode.length);
                } else if (declaredClasses.containsKey(binaryName)) {
                    throw new RuntimeException(
                        "Class " + binaryName + " was already loaded, " +
                        "it must not be redeclared");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(
            "could not load classes into ClassLoader", e);
    } finally {
        rehideMethod(findLoadedClass);
        rehideMethod(defineClass);
    }
}

private void rehideMethod(Method m) {
    if (m != null) {
        try {
            m.setAccessible(false);
        } catch (Exception e) {
        }
    }
}

这依赖于

private final DependencyDetector dependencies = new DependencyDetector();
private final Map<String, byte[]> declaredClasses = new HashMap<String, byte[]>();

private byte[] getBytecode(String binaryName) {
    byte[] bytecode = declaredClasses.get(binaryName);
    if (bytecode == null) {
        // asBytes loads the class as byte[]
        bytecode =
            asBytes(binaryName.replace('.', '/') + ".class");
    }
    return bytecode;
}

差不多就是这样,它在我迄今为止遇到的每一种情况下都很有效。

于 2012-09-12T13:34:24.073 回答
0

使用instance of 检查对象是否属于该类。

if (aAnimal instanceof Fish){
      Fish fish = (Fish)aAnimal;
      fish.swim();
    }
    else if (aAnimal instanceof Spider){
      Spider spider = (Spider)aAnimal;
      spider.crawl();
    }
于 2012-08-27T12:36:37.673 回答