How to use reflections in java

Reflections provide you access to other classes,methods and constructors from a loaded class.Manipulating methods,Fields,Constructors is possible through invoking different operations.

Reflections are often used in RPC(Remote Procedure Call) providing remote access to Constructors and Fields.

The main disadvantages using reflections are:

  • No compile Time checking

  • Performing complex access

  • low Perfomance

Advantages:

  • knowing compile time is not needed

  • modify runtime behaviour

Example:

In this example we try to access methods from the Matrix.class 

	public static void main(String[] args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
		// TODO Auto-generated method stub
		 Class<?> c = null;
		try {
			c = Class.forName("Matrix");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		   
			
            Method[] allMethods = c.getDeclaredMethods();
            for (Method m : allMethods) {
        		String mname = m.getName();
        		
           System.out.println(mname); 
	}
	}
}

Output:

add
init
setRandom
subtraction
multiplikation
output

invoke Methods with a help of reflections from Math.class 

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Scanner;
 
public class JMathReflect {
 
    static Class<Math> math = Math.class;
 
    public static void main(String[] args) {
 
        
        Method[] m = math.getMethods();
 
        
      
        String toTest;
        ArrayList<Method> al = new ArrayList<Method>();
 
        for (Method method : m) {
            toTest = method.toString();
            if (!toTest.contains(",") && !toTest.contains("()")
                    && toTest.contains("double")) {
                al.add(method);
            }
        }
 
        
        Scanner scan = new Scanner(System.in);
 
        System.out
                .println("JMathReflection Test: What method do you want to use? Eingabe z.B. sin\n");
 
        for (Method method : al) {
            System.out.println(method.toString());
        }
 
        String meth = scan.nextLine();
        System.out.println("please insert a value example: 10");
        Double value = Double.parseDouble(scan.nextLine());
        System.out.println("Your input is: " + meth + "(" + value
                + ")\nResult: ");
        scan.close();
 
     //call method from Arraylist
 
        for (Method method : al) {
            toTest = method.toString();
            if (toTest.contains("." + meth + "(")) {
 
                try {
                    Method forRes = java.lang.Math.class.getMethod(meth,
                            (double.class));
                    System.out.print(forRes.invoke(null, value));
                } catch (NoSuchMethodException | SecurityException
                        | IllegalAccessException | IllegalArgumentException
                        | InvocationTargetException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
 
            }
 
        }
 
    }
 
}

Leave a Reply