Nov 25, 2011

Classes at Runtime

Even at runtime, it is possible to access certain features of a class. This is done by way of the class Class, which implements a class descriptor object for a Java class. You can get a class descriptor from an existing class either by using the getClass() method of java.lang.Object or by calling the static method Class.forName():
Class stringClass = Class.forName("String");
Using a class descriptor, you can find out:
  • The class name
  • The superclass
  • Whether the class is actually an interface
  • Which interfaces the class implements
  • Which ClassLoader originated this class
There is also a way to instantiate new objects from the class descriptor: the newInstance() method. This has the limitation that no arguments can be passed to the constructor, so it fails unless the class has an accessible constructor which takes no arguments. There also doesn't seem to be any way to use the class descriptor to produce a valid operand for the right-hand side of instanceof.
Class java.lang.ClassLoader is meant to provide a way to load classes at runtime from a user-defined source. It is an abstract class. A subclass must implement the loadClass() method to load an array of bytes from somewhere and then convert it into a class descriptor by calling resolveClass() and defineClass().


Post a Comment