Here is an alternative answer without creating a new process via Runtime.getRuntime (). exec (...) - and you can also maintain your System.in/out channels. However, if you are new to the java programming world and trying to learn the ropes, I would suggest the following camickr advice and not mess with ClassLoader, as described below.
I assume that the class you need to run is self-contained (doesn't use inner classes) and is not yet in your classpath or jarfile, so you can just instantiate and call it main (). If there are multiple class files, simply repeat the method for loading them.
So in ActionListener, your JButton addActionListener () is ed to ...
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); }}
You will need the new MyClassLoader class already on your class path. Here is the pseudo code:
import java.io.*; import java.security.*; public class MyClassLoader extends ClassLoader { protected String classDirectory = "dirOfClassFiles" + File.separator, packageName = "packageNameOfClass."; private byte[] getBytes (String className) throws IOException { byte[] classBytes = null; File file = new File (classDirectory + className + ".class");
Notes: This works well when the class you are trying to load is on your local machine and you start java from the command line. I never managed to get an applet to load a class file from any servlet and load it - security will not allow this. In this case, the workaround is to simply launch another applet in a different window, but this is a different thread. The aforementioned class loading solves the problem of having to split every single file that you might need - just to run the GUI. Good luck, - M.S.
source share