Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

The Java documentation for Class says:

Class objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the defineClass 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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...