You cannot use .java files in runtime as they are not compiled yet. You have to find a .class or .jar file (or import the .java as a library and compile it with the rest of the project).
If you have the class's fully qualified name but for some reason can't access it at compile-time, you can use Class.forName(package.Class)
to load the class, and then call .getConstructor().newInstance()
to access its default (no argument) constructor. The resulting object will be an instance of the class. If you have to use this solution, I'd recommend you to do some research on reflection.
If you use the .java file as a library you can import it as a library using your IDE, if you google it there will be plenty of examples.
If you want to compile the file in runtime it will be a bit more difficult, but you can use the installed JDK for that:
JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
Or by executing the javac command in the command prompt via Runtime.getRuntime().exec()
. I'm not going to cover full solutions for these as they would be too long and you can find them elsewhere.
Note: If the class is not in your class path it is not loaded into the virtual machine. In this case (if it is compiled) you have to modify your JVM arguments to cover the file.
Edit: Code for runtime compilation via javac:
Process p = Runtime.getRuntime().exec(javac + " \"" + pathToFile + "\"");
p.waitFor();
This executes the javac command on your java file and creates a .class file in the same directory (I wrapped the path in "" to fix issues with path containing whitespaces).
Now you need to load the compiled class:
URL[] urls = new URL[]{new File(pathToFile).getParentFile().toURI().toURL()};
ClassLoader cl = new URLClassLoader(urls);
Class yourClass = cl.loadClass(className);
Then you can use the yourClass.getConstructor().newInstance() to create an instance of the class, as it is said in the first solution.