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
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{
}
915 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
574 Who developed the "avformat-59.dll" that comes with FFmpeg?
611 GDB gets version error when attempting to debug with the Presense SDK (IDE)
618 Uncaught (inpromise) Error on Electron: An object could not be cloned
© 2024 OneMinuteCode. All rights reserved.