
"Hi, Amigo!"
"Now it's time for the main event. We'll get acquainted with the Class class and touch on Reflection.
As you probably already realized, everything in Java is an object. And what does an object need? What does each object have that defines what it's all about?"
"A class!"
"Right! Well done. Each object has a class. But getting back to objects... Some objects entirely contain an entity, while others simply help manage it."
"This latter type includes FileOutputStream and Thread. When you create a Thread object, a new thread is not created. The thread is created by the Java virtual machine after the start() method is called. This object simply helps manage the process."
"Same with FileOutputStream: the file is stored on disk, and the OS manages storage and access. But we can interact with it through File objects, once again with the help of the Java virtual machine."
"Yes, I already understand that."
"So, there's a special class called Class for interacting with classes."
"That wasn't hard to guess."
"Yep. Each time the Java virtual machine loads a new class into memory, it creates a Class object, which you can use to get specific information about the loaded class."
"Each class and object is associated with a «Class object»."
Example | Description |
---|---|
|
Gets the Integer class's Class object. |
|
Gets the int class's Class object. |
|
Gets a String object's Class object. |
|
Gets the Object object's Class object. |
"Wow! How interesting!"
"Do you remember that the word class is a keyword in Java and can't be used as a variable name?"
"Oh yeah, I know, I know. I just forgot."
"Have you already used the Class object somewhere?"
"Yes, we used it when we wrote our own implementation of the equals method."
"Yes, you can use the getClass() method to test whether objects have the same class."
"And what can you do with this object?"
"Well, a lot of things:"
Java code | Description |
---|---|
|
Gets the class name. |
|
Gets a class by name. |
|
Compares objects' classes. |
"Interesting, but not as cool as I thought."
"You want it to be cool? There's also Reflection. Reflection is super cool."
"What's Reflection?"
"Reflection is a class's ability to obtain information about itself. Java has special classes: Field and Method, which are similar to the Class class for classes. Just as Class objects let you get information about a class, Field objects provide information about a field, and the Method object provides information about a method. And look at what you can do with them:"
Java code | Description |
---|---|
|
Gets a list of Class objects for the List class's interfaces |
|
Gets the Class object of the String class's parent class |
|
Gets a list of the List class's methods |
|
Creates a new String |
|
Gets the String class's length method and calls it on the String s |
"Wow! Now that's really cool!"
GO TO FULL VERSION