How to rename classes in a jar file
suggest changepublic static void main(String[] args) throws Exception {
File jarFile = new File("Input.jar");
Map<String, ClassNode> nodes = JarUtils.loadClasses(jarFile);
Map<String, byte[]> out = JarUtils.loadNonClassEntries(jarFile);
Map<String, String> mappings = new HashMap<String, String>();
mappings.put("me/example/ExampleClass", "me/example/ExampleRenamed");
out.putAll(process(nodes, mappings));
JarUtils.saveAsJar(out, "Input-new.jar");
}
static Map<String, byte[]> process(Map<String, ClassNode> nodes, Map<String, String> mappings) {
Map<String, byte[]> out = new HashMap<String, byte[]>();
Remapper mapper = new SimpleRemapper(mappings);
for (ClassNode cn : nodes.values()) {
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
ClassVisitor remapper = new ClassRemapper(cw, mapper);
cn.accept(remapper);
out.put(mappings.containsKey(cn.name) ? mappings.get(cn.name) : cn.name, cw.toByteArray());
}
return out;
}
SimpleRemapper is an ASM class (org.objectweb.asm.commons). A map entry from one internal name to another renames that class, and ClassRemapper rewrites references in every class passed to accept. Field and method renames use different keys, such as com/example/Type.field and com/example/Type.method(I)V. COMPUTE_FRAMES still needs common superclasses available while the classes are written. JarUtils is not part of ASM. The page "How to edit jar files with ASM" names the non-class loader loadNonClasses, not loadNonClassEntries.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents