Carbonizer Carbonizer - 1 year ago 42
Java Question

what is the Class object (java.lang.Class)?

The Java documentation for


objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the
method in the class loader.

What are these
objects? Are they the same as objects instantiated from a class by calling

Also, for example
how can everything be typecasted to superclass
, even if I don't inherit from

Answer Source

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:

  • name
  • package
  • methods
  • fields
  • constructors
  • annotations

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 enums and interfaces also represent a Class object, 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.