The Java documentation for Class
says:
Class
objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to thedefineClass
method in the class loader.
What are these Class
objects? Are they the same as objects instantiated from a class by calling new
?
Also, for example object.getClass().getName()
how can everything be typecasted to superclass Class
, even if I don't inherit from java.lang.Class
?
Nothing gets typecasted to Class
. Every Object
in Java belongs to a certain class
. That's why the Object
class, which is inherited by all other classes, defines the getClass()
method.
getClass()
, or the class-literal - Foo.class
return a Class
object, which contains some metadata about the class:
and some useful methods like casting and various checks (isAbstract()
, isPrimitive()
, etc). the javadoc shows exactly what information you can obtain about a class.
So, for example, if a method of yours is given an object, and you want to process it in case it is annotated with the @Processable
annotation, then:
public void process(Object obj) {
if (obj.getClass().isAnnotationPresent(Processable.class)) {
// process somehow;
}
}
In this example, you obtain the metadata about the class of the given object (whatever it is), and check if it has a given annotation. Many of the methods on a Class
instance are called "reflective operations", or simply "reflection. Read here about reflection, why and when it is used.
Note also that Class
object represents enums and intefaces along with classes in a running Java application, and have the respective metadata.
To summarize - each object in java has (belongs to) a class, and has a respective Class
object, which contains metadata about it, that is accessible at runtime.