对于我正在研究的项目,我正在尝试使用ASM重命名jar文件中的类。我已经开始运作了...但是有一个陷阱。在jar中重命名的每个类都有重复的字段。

这是我的代码:

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.commons.Remapper;
import org.objectweb.asm.commons.RemappingClassAdapter;
import org.objectweb.asm.commons.SimpleRemapper;
import org.objectweb.asm.tree.ClassNode;
//Imports showing which ASM (5.0.4) classes I'm using

private static void doStuff() throws IOException {
    File jar = new File("Input.jar");
    //Get's the ClassNodes for each class in a jar
    ArrayList<ClassNode> nodes = BCU.loadClasses(jar);
    //Appends '_Test' to each class except for the main class.
    Remapper mapper = new SimpleRemapper(getRename(nodes));
    //Loop through the ClassNodes updating references to renamed classes
    for (ClassNode cn : nodes) {
         ClassReader cr = new ClassReader(BCU.getNodeBytes(cn));
         ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_MAXS);
         RemappingClassAdapter rca = new RemappingClassAdapter(cw, mapper);
         cr.accept(rca, ClassReader.EXPAND_FRAMES);
         cr = new ClassReader(cw.toByteArray());
         cr.accept(cn,ClassReader.EXPAND_FRAMES);
    }
    //Export the nodes as a new jar file and copy over the META-INF folder
    BCU.saveAsJar(nodes, "Output.jar");
}


输出示例:

public static String VERSION;
public static final ConfigFile config;
public static String VERSION;
public static final ConfigFile_Test config;




编辑(3/28/2016):在学习了有关ASM的更多信息后回来,这里是应该如何做:

for (ClassNode cn : nodes.values()) {
    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    //mapper is a Remapper instance
    ClassVisitor remapper = new RemappingClassAdapter(cw, mapper);
    cn.accept(remapper);
    //out = Map<String, byte[]>
    out.put(renamed.get(cn.name).getRenamed(), cw.toByteArray());
}


锑是对的。当我发布此内容时,我最初的想法是编辑ClassNode本身(我有一个ClassNode扩展可以处理所有内容。这很讨厌)。自从迁移到Remapper实施以来,情况一直很好。

最佳答案

cr.accept(cn,ClassReader.EXPAND_FRAMES);


问题是您要在现有的ClassNode上调用accept。 ClassNode.visitField将一个字段添加到类节点。因此,ClassNode中的所有内容都会加倍-现有数据的一份副本和您添加的一份副本。

09-08 11:04