Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Nothing gets typecasted to <code>Class</code>. Every <code>Object</code> in Java belongs to a certain <code>class</code>. That's why the <code>Object</code> class, which is inherited by all other classes, defines the <code>getClass()</code> method.</p> <p><code>getClass()</code>, or the class-literal - <code>Foo.class</code> return a <code>Class</code> object, which contains some metadata about the class:</p> <ul> <li>name</li> <li>package</li> <li>methods</li> <li>fields</li> <li>constructors</li> <li>annotations</li> </ul> <p>and some useful methods like casting and various checks (<code>isAbstract()</code>, <code>isPrimitive()</code>, etc). <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Class.html" rel="noreferrer">the javadoc</a> shows exactly what information you can obtain about a class.</p> <p>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 <code>@Processable</code> annotation, then:</p> <pre><code>public void process(Object obj) { if (obj.getClass().isAnnotationPresent(Processable.class)) { // process somehow; } } </code></pre> <p>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 <code>Class</code> instance are called "reflective operations", or simply "reflection. <a href="http://download.oracle.com/javase/tutorial/reflect/index.html" rel="noreferrer">Read here</a> about reflection, why and when it is used.</p> <p>Note also that enums and interfaces also represent a <code>Class</code> object, and have the respective metadata.</p> <p>To summarize - each object in java has (belongs to) a class, and has a respective <code>Class</code> object, which contains metadata about it, that is accessible at runtime.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload