0

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.

3
  • 4
    The .java file needs to be compiled to a .class file first... Commented Sep 18, 2015 at 7:13
  • what are you expecting it to do? and what error does it give ? where do you define or give it className ? Commented Sep 18, 2015 at 7:15
  • possible duplicate of Java example with ClassLoader Commented Sep 18, 2015 at 7:17

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, it works after compilation. But when the file have imports there are errors during compilation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.