Search code examples
javaloadclassloaderdisk

JAVA - get class from file.java located on disk


I want to load class definitions or fields from file.java located on disk. I tried URLClassLoader:

URL url = file.toURL();
URL[] urls = new URL[]{url};
ClassLoader cl = new URLClassLoader(urls);
Class c = new Object().getClass();
try {
    c = cl.loadClass(className);
} catch (ClassNotFoundException e1) {
    System.err.println("not found class: " + className);
}

But it doesn't work.


Solution

  • You can load classes via loadClass, but not source code files. .java files contain source code. With Java, as with many (but not all) other languages, you must "compile" the source code into a machine-readable form — in the case of Java, a .class file (which may or may not then be bundled into a .jar). You compile Java code with the javac tool (or the features of your IDE).

    For instance, if you have a class called Foo defined in a file called Foo.java, then:

    javac Foo.java
    

    ...will create Foo.class, which can then be loaded.

    You may find this "Getting Started": The "Hello World" application tutorial from Oracle useful. It goes through the steps of getting the tools set up on your computer, writing a source file, compiling it into a class file, and running it.