这是一个替代答案,无需通过 Runtime.getRuntime().exec(...) 创建新进程 - 您也可以维护 System.in/out 通道。但是,如果您是 Java 编程世界的新手并试图学习其中的技巧,我建议您遵循 camickr 的建议,不要像下面描述的那样弄乱 ClassLoader。
我假设您需要运行的类是自包含的(不使用内部类)并且不在您的类路径或 jarfile 中,因此您可以创建一个实例并调用它的 main()。如果涉及多个类文件,只需重复加载它们的方法即可。
因此,在您的 JButton addActionListener() 的 ActionListener 中...
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 时,这很有效。我从来没有成功地尝试让一个小程序从某个 servlet 下载一个类文件并加载它——安全性不允许这样做。在这种情况下,解决方法就是在另一个窗口中运行另一个小程序,但那是另一个线程。上面的类加载解决了你可能需要的每一个类文件的问题 - 只是为了启动 GUI。祝你好运 - 女士