Friday, March 24, 2023

Working with java reflect

A simple code that i wanted to share:
List methods / attributes and the call of method without parameters

-Aclass is a simple class that will be loaded by java reflect
-An instance will be created and manipulated


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.exemple.reflect;
 
public final class Aclass {
     
    public int i;
     
    public Aclass() {
        i = 50;
    }
    public Aclass(int i) {
        this.i = i;
    }
     
    public int computeSquare() {
        return i*i;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.exemple.reflect;
 
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
 
public final class MainClass {
     
    private static String CLASS_NAME = "com.exemple.reflect.Aclass";
    private static Aclass instance;
    private static Class theClass;
     
    static {
      try {
              theClass = Class.forName(CLASS_NAME);
              instance = (Aclass) theClass.newInstance();
      }catch(Exception e) {
          e.printStackTrace();
      }
    }
 
    public static void main(String... args) {
        System.out.println("List of methods");
        Arrays.asList(theClass.getDeclaredMethods()).stream().forEach(System.out::println);
        System.out.println("List of attributes");
        Arrays.asList(theClass.getDeclaredFields()).stream().forEach(System.out::println);
        System.out.println("Running first method");
        Method method = theClass.getDeclaredMethods()[0];
        try {
            System.out.println(method.invoke(instance));
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            e.printStackTrace();
        }      
    }
}