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 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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…