Skip to content

Instantly share code, notes, and snippets.

@DataPools
Last active July 21, 2023 03:36
Show Gist options
  • Save DataPools/9c66bec1c9de1bbb626137056d788fa7 to your computer and use it in GitHub Desktop.
Save DataPools/9c66bec1c9de1bbb626137056d788fa7 to your computer and use it in GitHub Desktop.
Method to edit a method inside a .jar file using Javassist
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;
public class EditMethod {
public static void modifyJar(String pathToJAR, String pathToClassInsideJAR, String methodName, String type, String codeToSetMethod) throws IOException, CannotCompileException, NotFoundException {
//REQUIRES JAVASSIST
JarFile jarFile = new JarFile(pathToJAR);
ZipEntry zipEntry = jarFile.getEntry(pathToClassInsideJAR);
InputStream fis = jarFile.getInputStream(zipEntry);
ClassPool pool = ClassPool.getDefault();
CtClass cc = pool.makeClass(fis);
fis.close();
jarFile.close();
//Type should be in this format: "()Ljava/lang/String;" (example for String)
CtMethod cm = cc.getMethod(methodName, type);
cm.setBody(codeToSetMethod);
//Replace Windows's Stupid backslashes
String classFileName = pathToClassInsideJAR.replace("\\", "/").substring(0, pathToClassInsideJAR.lastIndexOf('/'));
DataOutputStream out = new DataOutputStream(new FileOutputStream(classFileName));
cc.getClassFile().write(out);
Map<String, String> launchenv = new HashMap<>();
URI launchuri = URI.create("jar:"+new File(pathToJAR).toURI());
launchenv.put("create", "true");
try (FileSystem zipfs = FileSystems.newFileSystem(launchuri, launchenv)) {
Path externalClassFile = Paths.get(classFileName);
Path pathInJarfile = zipfs.getPath(pathToClassInsideJAR);
// copy a file into the zip file
Files.copy( externalClassFile,pathInJarfile,
StandardCopyOption.REPLACE_EXISTING );
}
}
}
@pp0236
Copy link

pp0236 commented Feb 22, 2022

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment