I want to load class definition 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 doesnt work ;(
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.