You want to get a Class
object from a class name or instance.
If the type name is known at compile time, you can get the class instance using the compiler keyword .class
, which works on any type that is known at compile time, even the eight primitive types.
Otherwise, if you have an object (an instance of a class), you can call the java.lang.Object
method getClass()
, which returns the Class object for the object’s class.
You need to find arbitrary method or field names in arbitrary classes.
Use the reflection package java.lang.reflect
.
You want to load classes dynamically, just like web servers load your servlets.
Use class.forName("ClassName");
and the class’s newInstance()
method.
You need to load a class from a nonstandard location and run its methods.
Examine the existing loaders such as java.net.URLClassLoader
. If none is suitable, write and use your own ClassLoader
.
You’d rather construct a class dynamically by generating source code and compiling it.
Use the JavaCompiler from javax.tools
.