URLClassLoaderの+はloadClass +スタンドアロンプロセスのmainメソッドを呼び出しますか?ジャワ
-
19-09-2019 - |
質問
私は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) {
}
}
それは別のプロセスでこれを起動することは可能ですか?だから、実行中のアプリケーションと新しい呼び出されたアプリケーションが共通して何もない?
状況:あなたがプログラムA(クライアントアップデータ)を起動します。クライアントAからは、プログラムB(クライアント)を起動
現在のコード、プロジェクトAとプロジェクトBを共有し、同じヒープ領域のすべてのインスタンスで。私はプロジェクトBのすべてのインスタンスは、スタンドアロンされ、プロジェクトAが終了されているかどうかを気にしない状態を達成しようとしています。
解決
はい、実際にそれは完全にその反映処理を実行する必要がなくなります。
あなたが使用する必要があります ProcessBuilderを別の仮想マシンに新しいプロセスを開始します。
のような何かます:
ProcessBuilder pb = new ProcessBuilder("java", "-jar", f.getAbsolutePath());
Process p = pb.start();
編集
- ?ということな作業pb.startないプログラムは、()終了した場合の
- Javaの環境変数が設定されていない場合に動作します。の
[マック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
所属していません StackOverflow