這裏是沒有形成通過調用Runtime.getRuntime一個新的進程的備選答案()EXEC(...) - 你可以保持您的System.in/out渠道了。但是,如果你是Java編程領域的新手,並試圖學習繩索,我會建議遵循camickr的建議,而不是像下面描述的那樣搞亂ClassLoader。
我假設你需要運行的類是自包含的(不使用內部類),也不在你的類路徑或jar文件中,所以你可以創建一個實例並調用它的main()。 如果涉及多個類文件,只需重複加載它們的方法即可。
所以,在ActionListener的,你的JButton addActionListener方法() - ED來...
public void actionPerformed (ActionEvent e) {
String classNameToRun = e.getActionCommand(); // Or however you want to get it
try {
new MyClassLoader().getInstance(classNameToRun).main (null);
} catch (ClassNotFoundException ce) {
JOptionPane.showMessageDialog (null, "Sorry, Cannot load class "+classNameToRun,
"Your title", JOptionPane.ERROR_MESSAGE);
}}
您將需要一個新的類MyClassLoader已經在你的類路徑中。下面是一個僞代碼:
import java.io.*;
import java.security.*;
public class MyClassLoader extends ClassLoader {
protected String classDirectory = "dirOfClassFiles" + File.separator,
packageName = "packageNameOfClass.";
/**
* Given a classname, get contents of the class file and return it as a byte array.
*/
private byte[] getBytes (String className) throws IOException {
byte[] classBytes = null;
File file = new File (classDirectory + className + ".class");
// Find out length of the file and assign memory
// Deal with FileNotFoundException if it is not there
long len = file.length();
classBytes = new byte[(int) len];
// Open the file
FileInputStream fin = new FileInputStream (file);
// Read it into the array; if we don't get all, there's an error.
// System.out.println ("Reading " + len + " bytes");
int bCount = fin.read (classBytes);
if (bCount != len)
throw new IOException ("Found "+bCount+" bytes, expecting "+len);
// Don't forget to close the file!
fin.close();
// And finally return the file contents as an array
return classBytes;
}
public Class loadClass (String className, boolean resolve)
throws IOException, ClassNotFoundException,
IllegalAccessException, InstantiationException {
Class myClass = findLoadedClass (packageName + className);
if (myClass != null)
return myClass;
byte[] rawBytes = getBytes (className);
myClass = defineClass (packageName + className,
rawBytes, 0, rawBytes.length);
// System.out.println ("Defined class " +packageName + className);
if (myClass == null)
return myClass;
if (resolve)
resolveClass (myClass);
return myClass;
}
public Object getInstance (String className) throws ClassNotFoundException {
try {
return loadClass (className, true).newInstance();
} catch (InstantiationException inExp) { inExp.printStackTrace();
} catch (IllegalAccessException ilExp) { ilExp.printStackTrace();
} catch (IOException ioExp) { ioExp.printStackTrace();
}
return null;
}
}
注: 這種運作良好,當你試圖加載類是駐留在本地機器上,你正在運行的命令行的Java。我從來沒有成功嘗試讓applet從某個servlet下載一個類文件並加載它 - 安全性不允許這樣做。在這種情況下,解決方法只是在另一個窗口中運行另一個applet,但這是另一個線程。上面的類加載解決了必須激發您可能需要的每個類文件的問題 - 只需啓動GUI即可。祝你好運, - M.S.
注:我在java中編寫了一個mainProgram類,並使用該類創建了.exe文件。但是,而不是使用.exe文件,是否有可能使用我的JButton啓動類(使用mainProgram)?如果是,我應該爲actionListener寫什麼? – Mike 2011-01-23 04:48:22