What is Reflection in Java?

Asked 2 years ago, Updated 2 years ago, 112 views

I saw the Reflection technique while I was googling, but I don't understand it well with my head. Can you show me a simple example that will help me understand the concept of reflection?

java reflection

2022-09-22 22:14

1 Answers

Reflection is used to investigate the class. You can get if you have a particular type of method (return type, parameter), what the fields have, whether they are private or public.

I used reflection to see if a particular method uses an annotation that I set. Like the following code, you can make a reflection called @RunTwice and select only the method with the reflection and run it twice. @RunTwice, put anything between methods 1 and 3 and run it.

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.*;


class Solution {
  public static void main(String[] args) {
    Solution solution = new Solution();

    //Read and investigate all methods in the Solution class
    Method[] methods = solution.getClass().getDeclaredMethods();
    for(Method method : methods){
      if(method.isAnnotationPresent(RunTwice.class)){
        try{
          //Do it twice as your name says.
          method.invoke(solution);
          method.invoke(solution);
        }
        catch(Exception e){
          e.printStackTrace();
        }
      }      
    }
  }

  @RunTwice  
  public void method1(){
    System.out.println ("Method 1")
  }

  public void method2(){
    System.out.println ("Method 2")
  }

  public void method3(){
    System.out.println ("Method 3").");
  } 
}

//Create an annotation called Run Twice
@Retention(RetentionPolicy.RUNTIME)
@interface RunTwice{

}



2022-09-22 22:14

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.