August 4, 2022

Java Reflection – Arrays

Since array in Java is also a class so many of the methods in java.lang.Class can be used with the array too. Apart from that in Java Reflection API there is a class java.lang.reflect.Array that has methods for creating new arrays, getting and setting array elements at run time.

Identifying array type using Java Reflection

To identify if any of the class field is of array type you can use Class.isArray() method. Following class is used for example purpose with an array field.

public class Message {
  String msg;
  private int[] codeArray;

  public void displayMessage(){
    System.out.println(msg);
  }
}
import java.lang.reflect.Field;

public class ReflectionDemo {
  public static void main(String[] args) {
    try {
      // get instance of Class
      Class<?> cls = Class.forName("com.knpcode.programs.Message");	
      Field[] fields = cls.getDeclaredFields();
      for (Field f : fields) {
        Class<?> type = f.getType();
        // Looking for array
        if(type.isArray()){
          System.out.println("Array found- " + f.getName());
        }
      }		   		           
    } catch (IllegalArgumentException | ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}
Output
Array found- codeArray

Creating new array using Java Reflection

Java Reflection API provides the ability to dynamically create arrays of arbitrary type and dimensions using java.lang.reflect.Array.newInstance() method.

public class ReflectionDemo {
  public static void main(String[] args) {
    int[] codesArray = (int[])Array.newInstance(int.class, 5);
    System.out.println("Array of length " + codesArray.length + " created.");
  }
}
Output
Array of length 5 created.

Get/set elements of array using Java Reflection

For getting and setting elements of an array there are several setters and getters in java.lang.reflect.Array for different types like setByte(), setDouble(), getInt(), getFloat() and there is also generic get() and set() method.

  • set(Object array, int index, Object value)- Sets the passed value in the specified array at the given index.
  • get(Object array, int index)- Returns the value at the sepcified index in the specified array object.
import java.lang.reflect.Array;

public class ReflectionDemo {
  public static void main(String[] args) {
    int[] codesArray = (int[])Array.newInstance(int.class, 5);
    System.out.println("Array of length " + codesArray.length + " created.");
    //using set method to set value
    Array.set(codesArray, 0, 3);
    // Setting values using setInt method
    Array.setInt(codesArray, 1, 10);		
    Array.setInt(codesArray, 2, 4);
    
    // Getting values using getInt and get methods
    System.out.println("Value at index 0- " + Array.get(codesArray, 0));
    System.out.println("Value at index 1- " + Array.getInt(codesArray, 1));
    System.out.println("Value at index 2- " + Array.getInt(codesArray, 2));
  }
}
Output
Array of length 5 created.
Value at index 0- 3
Value at index 1- 10
Value at index 2- 4

That's all for the topic Java Reflection – Arrays. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment