Which method is used to access a private field using Java Reflection?

Java MCQ: Which method is used to access a private field using Java Reflection?

a) getField()
b) getDeclaredField()
c) getPrivateField()
d) accessField()

Answer:

b) getDeclaredField()

Explanation:

The getDeclaredField() method in Java is used to access a private field of a class using reflection. This method is part of the Class class and returns a Field object representing the specified field. The getDeclaredField() method allows you to access fields regardless of their access modifiers, including private fields.

Here’s an example of how to use getDeclaredField() to access a private field:

import java.lang.reflect.Field;

public class AccessPrivateFieldExample {
    public static void main(String[] args) {
        try {
            MyClass obj = new MyClass();
            Field field = MyClass.class.getDeclaredField("privateField");
            field.setAccessible(true);
            field.set(obj, "New Value");
            System.out.println("Private field value: " + field.get(obj));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class MyClass {
    private String privateField = "Initial Value";
}

In this example, getDeclaredField() is used to obtain a Field object representing the private field privateField in the MyClass class. The setAccessible(true) method is then called to bypass the access control checks, allowing the private field to be modified and accessed. The field is then set to a new value and printed to the console.

Accessing private fields via reflection is a powerful feature, but it should be used with caution as it can break encapsulation, one of the key principles of object-oriented programming. It also has implications for security and maintainability, so it is generally advised to limit its use to specific scenarios such as testing or working with legacy code.

Reference links:

https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top