What is Reflection in Java?

Reflection is the ability of a program to analyze or change its own structure at runtime.

Reflection in Java

In Java, Reflection can be used to read information about classes. This includes modifiers, variables, constructors, methods, annotations, etc. Another field of application is the use of code analysis tools or debuggers.

In a simple example, we can show how Reflection can analyze the following class.

public class Person
    private String firstName;
    private String lastName;

    public Person(String firstName, String lastName)
        this.firstName = firstName;
        this.lastName = lastName;

    // Getter, Setter, toString() etc...
This class can now be analyzed at runtime using reflection:

Class person = Person.class;

Field[] fields = person.getDeclaredFields();

for (int i = 0; i < fields.length; i++) 

The output of the program looks like this:


Note that the fields that have been read, although they are declared as private. So you should be aware that the inner structure of classes in Java is never completely secret and can be read and even modified!
java-mcq-multiple-choice-questions-and-answersJava MCQ – Multiple Choice Questions and Answers – OOPsThis collection of Java Multiple Choice Questions and Answers (MCQs): Quizzes & Practice Tests with Answer focuses on “Java OOPs”.   1. Which of the…Read More


Advantages and disadvantages of reflection

Of course, every technology has its advantages and disadvantages.

  • Knowledge is power: With Reflection, you can read and modify classes at runtime.
  • Extensibility: You can flexibly determine which methods you want to call or which class you want to instantiate. That makes e.g. extension possible by Plugins.
  • Configuration with annotations: As already known from many libraries classes, variables or methods can be provided with annotations.
  • Breaking encapsulation: Reflection allows the modifiers to be changed, e.g. private in public. The developer has usually made a variable private for a reason.
  • Security: Reading and changing classes can definitely also influence security aspects. In some environments, access is not possible at all.
  • Performance: Reflection can have a negative impact on performance because the JVM cannot optimize it.
Java 8 Stream TutorialJava 8 Stream TutorialOne of the big innovations of Java 8 is the new Streams API (Package A stream in the sense of this API is simply…Read More mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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