Biscuit128
Biscuit128

Reputation: 5398

How does a class loader find a class

ClassLoader c //imagine this is a valid object
c.loadClass(String className, boolean resolveIt); 

It is the className parameter which is confusing me. I have written the java file to a folder, and compiled it using reflection. I am unsure therfore how I point to the correct file and what naming convention i use for the className.

The documentation sayjust says the name of the class, but how is it supposed to know where it is?

Thanks

Upvotes: 0

Views: 147

Answers (2)

Ingo
Ingo

Reputation: 36329

This is the very reason why you write a classloader in the first place: it is just a mechanism to map class names to (binary) classes in memory. Where the classloader gets the data is its very own business.

For example, an URLClassLoader will consult the class path and see if it can find a file that contains the named class.

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691635

The point of a ClassLoader is precisely to know how to search for class files given a class name. The javadoc says:

Given the binary name of a class, a class loader should attempt to locate or generate data that constitutes a definition for the class. A typical strategy is to transform the name into a file name and then read a "class file" of that name from a file system.

So, you'll have to make your ClassLoader translate the class name to some location where the byte-code of the class will be found. URLClassLoader does that by transforming the class name into a path, and looking up that path in the various jars and directories at which the URLs point.

Upvotes: 2

Related Questions