Java Reflection Tutorial
Reflection is the ability for a class or object to examine itself at runtime. In addition, reflection lets Java look at the class of the object and determine its structure. As defined by the security manager, you will be able to find out the constructors, interfaces, methods, annotations, and fields a class has as well as its attributes. In addition, you can change the value of fields, invoke methods, and invoke new objects.
Put another way, reflection allows us to do the following:
- We can construct objects dynamically at runtime
- Gather details about an object’s class
- Determine a class’s structure at runtime (name, fields, methods)
- Change the values of a class’s fields
- Invoke an objects methods at runtime
Although there are many Java Reflection Tutorials available online, I hope that this Java Reflection Tutorial will give you a deeper understanding of how you can use many of the features available.
If you have been around for a short while and are familiar with Java and the tools used in the industry then you have already been using Reflection by some of these tools and applications.
Tools using Reflection
- Spring (For Dependency Injection)
- The Eclipse IDE
- JUnit (for annotation)
In this Java Reflection Tutorial series, we will discuss many of the different aspects of Java Reflection API.
Java Reflection Examples
- Class Example
Simple example shows you how to dynamically load and instantiate a class, get class name, package name, and superclass name.
- Modifier Example
Showing you how to get information about classes, fields and methods using modifier method.
- Method Example
Providing full details of how to get all methods, and invoke methods using reflection.
Frequently Asked Questions on Java Reflection API (FAQs)
- Different ways that I can get Class objects in Java using Reflection?
- How do I instantiate a class with a private constructor?
- How do I a list of all of the class's constructors?
- How do I list public methods of a class using Reflection?
- How do I list declared methods of a class using Reflection?
- How do I list all the methods of a class using Reflection?
- How do I get a list of class modifiers?
- Hacking Immutable class using Java Reflection
- Hacking the Immutable String class using Java Reflection