我有两个jar文件(为了举例方便,我们称它们为Updater.jar和Code.jar)。 Updater.jar 使用其主方法启动,然后再使用其premain方法启动自身:
package Update;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
public class InstructionLauncher {
private List<UpdateInstruction> instructions = new ArrayList<UpdateInstruction>();
private static InstructionLauncher instance;
private Process process;
public static InstructionLauncher initialise(){
if(instance !=null) return instance;
else return new InstructionLauncher();
}
public void registerPremain(UpdateInstruction inst){
instructions.add(inst);
}
public void launchNext(){
UpdateInstruction inst = instructions.get(0);
String cls = inst.getClassName() + "." + inst.getMethodName();
String[] args = new String[]{"java", "-javaagent", "JOSUpdater.jar", "-jar", inst.getClassName() + "." + inst.getMethodName()};
ProcessBuilder builder = new ProcessBuilder(args);
try {
exportResource(cls, cls);
} catch (Exception e) {
UpdateManager.revert();
}
try {
Process p = builder.start();
process = p;
} catch (IOException e) {
e.printStackTrace();
}
while(!process.isAlive())launchNext();
}
private InstructionLauncher(){
instance = this;
}
//From https://dev59.com/wWkv5IYBdhLWcg3w1kWr
private String exportResource(String resourceName, String clazz) throws Exception {
InputStream stream = null;
OutputStream resStreamOut = null;
String jarFolder;
try {
stream = Class.forName(clazz).getResourceAsStream(resourceName);//note that each / is a directory down in the "jar tree" been the jar the root of the tree
if(stream == null) {
throw new Exception("Cannot get resource \"" + resourceName + "\" from Jar file.");
}
int readBytes;
byte[] buffer = new byte[4096];
jarFolder = new File(Class.forName(clazz).getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParentFile().getPath().replace('\\', '/');
resStreamOut = new FileOutputStream(jarFolder + resourceName);
while ((readBytes = stream.read(buffer)) > 0) {
resStreamOut.write(buffer, 0, readBytes);
}
} catch (Exception ex) {
throw ex;
} finally {
stream.close();
resStreamOut.close();
}
return jarFolder + resourceName;
}
}
目前,premain方法如下所示:
package Update;
import java.lang.instrument.Instrumentation;
public class PremainLauncher {
public static void premain(String args, Instrumentation inst){
inst.addTransformer(new Transformer(), true);
System.out.println("Registered instruction for package: " + args);
}
}
我想知道如何将整个外部JAR(例如Code.jar)添加到检测路径中?
我知道Instrumentation.retransformClasses方法,但是要使用它,我需要获取该jar中所有类的List>,但我一直无法完成。
假设Code.jar有三个类文件:Main.class,writer.class和display.class。有没有办法获取每个类对象的列表,而不是它们的名称?
System.setProperty("java.library.path", System.getProperty("java.library.path" + File.separator + "JOSUser.jar");
吗?还是说这样会有不同的效果?我更倾向于以编程的方式回答此问题,而不是使用命令行。 - JD9999