Introduction
This series is going to be dedicated to the basic understanding of Java. When ever I find myself asking, "How does this work ?". I will create a blog post and put it here. This series will not be in order so feel free to read what ever post you find most relevant.
Ok I am not 100% sure about the correctness of this blog post but I have been reading stack overflow and JVM specification documents for the last couple hours and this is what I have come up with. If you see that I am missing anything please comment below.
What is .class?
- the
.class
is representing what is called aclass literal
in Java. A class literal is an expression consisting of the name of a class, interface, array or primitive type followed by.class
. A class literal evaluates to a Class object for the named type. - For example if you have C.class, where C is the name of a class. The class literal will evaluate to a class object of type C, like so:
C.class ---evaluates to---> Class<C>
What is a class object and why is it generic?
- Well, instances of
Class
represent classes and interfaces in a running Java application. A Class has no public constructor, instead Class objects are constructed automatically by the JVM as classes are loaded by the defined class loader. Ok, that sort of makes sense but why is it generic? That seems to be due to changes made in JDK 5.0 where Class was made generic in order to help with modeling the class it is representing. See the code snippet above for an example.
Why use a class literal?
- Again, not 100% sure, I have seen class literals used in JUnit and all over the Android System. However, they all seem to point back to the Java Reflections API. Which is commonly used by programs which require the ability to examine or modify the runtime behaviour of applications running in the JVM. The reflections API specifically states,
For every type of object, the Java virtual machine instantiates an immutable instance of java.lang.Class which provides methods to examine the runtime properties of the object including its members and type information
.
Summary
- So basically any time you see
.class
know that aclass literal
is being used. A class literal being a creation of the Class object of whatever type .class follows. Class objects are created automatically by the JVM. The code that uses a class literal syntax is most likely making use of the Reflections API which provides methods to examine the runtime properties.
Conclusion
- Thank you for taking the time out of your day to read this blog post of mine. If you have any questions or concerns please comment below or reach out to me on Twitter.
Top comments (0)