Pee*_*ter 4 java process invoke urlclassloader
我正在使用以下方法来调用jar文件中的类:
invokeClass("path.to.classfile", new String[] {});
public static void invokeClass(String name, String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, MalformedURLException {
File f = new File(System.getProperty("user.home") + File.separator + ".myapplication"+File.separator+"myjar.jar");
URLClassLoader u = new URLClassLoader(new URL[]{f.toURI().toURL()});
Class c = u.loadClass(name);
Method m = c.getMethod("main", new Class[] { args.getClass() });
m.setAccessible(true);
int mods = m.getModifiers();
if (m.getReturnType() != void.class || !Modifier.isStatic(mods) || !Modifier.isPublic(mods)) {
throw new NoSuchMethodException("main");
}
try {
m.invoke(null, new Object[] { args });
} catch (IllegalAccessException e) {
}
}
Run Code Online (Sandbox Code Playgroud)
是否可以在单独的进程上调用它?那么正在运行的应用程序和新调用的应用程序没有任何共同之处?
情况:您启动程序a(客户端更新程序).从客户端启动程序b(客户端)
使用当前代码,项目a AND项目b的所有实例共享相同的堆空间.我试图实现,其中项目B的所有实例都是独立的,如果一个项目终止与否无所谓的状态.
是的,实际上这使您无法完全执行该反射过程
您需要使用ProcessBuilder在单独的虚拟机中启动新进程.
就像是:
ProcessBuilder pb = new ProcessBuilder("java", "-jar", f.getAbsolutePath());
Process p = pb.start();
Run Code Online (Sandbox Code Playgroud)
编辑
- 如果执行pb.start()的程序终止,那会起作用吗?
- 如果未设置java环境变量(例如Mac OS X?)[无法在mac os x上测试],那会起作用吗?
确实如此.看看这个视频:
http://img33.imageshack.us/img33/8380/capturadepantalla201001s.png
源代码(导入省略):
// MainApp.java
public class MainApp {
public static void main( String [] args ) throws IOException {
JFrame frame = new JFrame("MainApp");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new JLabel("<html><font size='48'>Main App Running</font><html>") );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
launchSeparateProcess();
frame.addWindowListener( new WindowAdapter() {
public void windowClosing( WindowEvent e ){
System.out.println("MainAppp finished");
}
});
}
private static void launchSeparateProcess() throws IOException {
File f = new File("./yourjar.jar");
ProcessBuilder pb = new ProcessBuilder("java", "-jar", f.getAbsolutePath() );
Process p = pb.start();
}
}
//-- Updater.jar
public class Updater {
public static void main( String [] args ) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new JLabel("<html><font size='78'>Updating....</font></html>"));
frame.pack();
frame.setVisible(true);
}
}
//--manifest.mf
Main-Class: Updater
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1919 次 |
| 最近记录: |