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


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;
    }
}
 

  

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();
        }       
    }
} 

No comments:

Post a Comment