Curriculum
In Java, reflection is a powerful mechanism that allows you to inspect and manipulate the behavior of classes, objects, and interfaces at runtime. Reflection allows you to examine the internal state of objects, access private fields and methods, and create new instances of classes, among other things. Reflection is useful when you need to dynamically modify the behavior of your program or work with classes that you don’t have access to at compile time.
Here’s an example of how to use reflection in Java:
public class MyClass { private int myPrivateField; public void setMyPrivateField(int value) { myPrivateField = value; } } public class ReflectionExample { public static void main(String[] args) throws Exception { MyClass myObject = new MyClass(); Class<?> myClass = myObject.getClass(); Field myField = myClass.getDeclaredField("myPrivateField"); myField.setAccessible(true); myField.setInt(myObject, 42); Method myMethod = myClass.getDeclaredMethod("setMyPrivateField", int.class); myMethod.invoke(myObject, 42); } }
In this example, we have a class called MyClass
with a private field called myPrivateField
and a public method called setMyPrivateField()
. In our ReflectionExample
class, we create an instance of MyClass
and then use reflection to access and modify the private field and invoke the public method.
We start by getting the class object for MyClass
using the getClass()
method. We then use the getDeclaredField()
method to get a reference to the private field, and we use the setAccessible()
method to make the field accessible. We can then use the setInt()
method to set the value of the private field.
Next, we use the getDeclaredMethod()
method to get a reference to the setMyPrivateField()
method, and we use the invoke()
method to call the method on our object.
Here are some rules to keep in mind when working with reflection in Java:
newInstance()
method or the Constructor
class.Annotation
interface and related classes.Type
interface and related classes.