-2

When a java program dynamically load a .class file,

  • Is only the fully qualified classname of the .class file needed? Does ClassLoader s method loadClass() only require the fully qualified classname of the .class file to be dynamically loaded?

  • If the .class file can be located anywhere in a filesystem, how can I specify its pathname in its filesystem?

  • When running such the bytecode create from a Java program with command java, do I need to specify the path of the .class file to be dynamically loaded in -cp?

Thanks.

Tim
  • 1
  • 141
  • 372
  • 590

1 Answers1

2

You are conflating classes and ".class" files.

Is only the fully qualified classname of the .class file needed? Does ClassLoader s method loadClass() only require the fully qualified classname of the .class file to be dynamically loaded?

The fully qualified class name of the class is required.

If the .class file can be located anywhere in a filesystem ...

It cannot be! The .class file corresponding to the class needs to be on the relevant classloader's classpath.

If you want to load a class from an arbitrary file in the file system, you need to create a new classloader instance:

  • If you use one of the standard classloader implementations, it will use the standard scheme for resolving a .class file location based on the classes package names.

  • It would be possible to implement a custom classloader that resolves FQ classnames to file system objects ... some other way. But that seems unnecessary, since a standard Java compiler will emit .class files as per the standard scheme.

When running such the bytecode create from a Java program with command java, do I need to specify the path of the .class file to be dynamically loaded in -cp?

You don't give the location of the .class file. You give the location of a directory where the .class file can be resolved, as above.

But if a running Java program generates, compiles and then loads a class, it will need to dynamically create a new classloader to load it ... reliably.

Why? Because classloaders typically cache the contents of directories and JAR indexes on the classpath. So when a program writes a new file, the classloader may not get to know about it.

There is also the issue that a classloader cannot load the same class (from any location) twice.

Finally, be aware that if two classloaders load a class with the same fully qualified name, the runtime type system treats them as distinct classes / types. You can't cast between the two incarnations of the type.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216