The Wayback Machine - https://web.archive.org/web/20240926222401/https://www.geeksforgeeks.org/reflection-array-class-in-java/
Open In App

Reflection Array Class in Java

Last Updated : 06 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The Array class in java.lang.reflect package is a part of the Java Reflection. This class provides static methods to create and access Java arrays dynamically. It is a final class, which means it can’t be instantiated or changed. Only the methods of this class can be used by the class name itself.

The java.util.Arrays class contains various methods for manipulating arrays (such as sorting and searching), whereas this java.lang.reflect.Array class provides static methods to create and access Java arrays dynamically. This Array class keeps the array to be type-safe.

Class Hierarchy 

java.lang.Object
↳ java.lang.reflect.Array

Class Declaration 

public final class Array 

Note: The Array class should be correctly represented as public final class Array. It extends Object implicitly but does not explicitly declare extends Object.

Syntax to use Array:

Array.<function name>;

Methods in Reflection Array Class in Java

S. No.MethodDescription
1Object get(Object array, int index)This method returns the value of the indexed component in the specified array object.
2boolean getBoolean(Object array, int index)This method returns the value of the indexed component in the specified array object as a boolean.
3byte getByte(Object array, int index)This method returns the value of the indexed component in the specified array object as a byte.
4char getChar(Object array, int index)This method returns the value of the indexed component in the specified array object as a char.
5double getDouble(Object array, int index)This method returns the value of the indexed component in the specified array object as a double.
6float getFloat(Object array, int index)This method returns the value of the indexed component in the specified array object as a float.
7int getInt(Object array, int index)This method returns the value of the indexed component in the specified array object as an int.
8int getLength(Object array)This method returns the length of the specified array object as an int.
9long getLong(Object array, int index)This method returns the value of the indexed component in the specified array object as a long.
10short getShort(Object array, int index)This method returns the value of the indexed component in the specified array object as a short.
11Object newInstance(Class<E> componentType, int length)This method creates a new array with the specified component type and length.
12Object newInstance(Class<E> componentType, int… dimensions)This method creates a new array with the specified component type and dimensions.
13void set(Object array, int index, Object value)This method sets the value of the indexed component of the specified array object to the specified new value.
14void setBoolean(Object array, int index, boolean z)This method sets the value of the indexed component of the specified array object to the specified boolean value.
15void setByte(Object array, int index, byte b)This method sets the value of the indexed component of the specified array object to the specified byte value.
16void setChar(Object array, int index, char c)This method sets the value of the indexed component of the specified array object to the specified char value.
17void setDouble(Object array, int index, double d)This method sets the value of the indexed component of the specified array object to the specified double value.
18void setFloat(Object array, int index, float f)This method sets the value of the indexed component of the specified array object to the specified float value.
19void setInt(Object array, int index, int i)This method sets the value of the indexed component of the specified array object to the specified int value.
20void setLong(Object array, int index, long l)This method sets the value of the indexed component of the specified array object to the specified long value.
21void setShort(Object array, int index, short s)This method sets the value of the indexed component of the specified array object to the specified short value. 

How to create an Array using java.lang.reflect.Array Class?

Creating an array using reflect.Array Class is different from the usual way. The process to create such an array is as follows: 

  • Get the size of the array to be created
  • To create an array (say of X class), use the newInstance() method of Array class to pass the X class as the type of the array, and the size of the array, as parameters.

Syntax: 

X[] arrayOfXType = (X[]) Array.newInstance(X.class, size);

Where X is to be replaced by the type of the array like int, double, etc.

  • This method returns an Object array of the given size, then cast into the required X[] type.
  • Hence the required array of type X has been created.

Below is an example to create an integer array of size 5, using the Array class:

Example: To create an integer array of size 5: 

Java
// Java code to create an integer array of size 5,
// using the Array class:

import java.lang.reflect.Array;
import java.util.Arrays;

public class GfG {
    public static void main(String[] args)
    {

        // Get the size of the array
        int sizeOfArray = 5;

        // Create an integer array
        // using reflect.Array class
        // This is done using the newInstance() method

        int[] intArray = (int[])Array.newInstance(
            int.class, sizeOfArray);
      
        // Printing the Array content
        System.out.println(Arrays.toString(intArray));
    }
}

Output
[0, 0, 0, 0, 0]

How to add elements in an Array using java.lang.reflect.Array Class?

Like creating an array, adding elements in the array using reflect.Array Class is also different from the usual way. The process to add elements in such an array is as follows: 

  • Get the value of the element to be added.
  • Get the index at which the element is to be added.
  • To add an element in an array (say of X class), use the setX() method of Array class, where X is to be replaced by the type of the array such as setInt(), setDouble(), etc. This method takes the X[] as the first parameter, the index at which the element is added as the second parameter, and the element as the third parameter in the below syntax.

Syntax: 

Array.setX(X[], indexOfInsertion, elementToBeInserted);

Where X is to be replaced by the type of the array like int, double, etc.

  • This method inserts the element at the specified index in this array.
  • Hence the required element has been inserted into the array.

Below is an example to add an element into an integer array, using the Array class:

Example: To add an element into an integer array: 

Java
// Java code to add an element into an integer array,
// using the Array class:

import java.lang.reflect.Array;
import java.util.Arrays;

public class GfG {
    public static void main(String[] args)
    {

        // Get the size of the array
        int sizeOfArray = 3;

        // Create an integer array
        // using reflect.Array class
        // This is done using the newInstance() method
        int[] intArray = (int[])Array.newInstance(
            int.class, sizeOfArray);

        // Add elements to the array
        // This is done using the setInt() method
        Array.setInt(intArray, 0, 10);
        Array.setInt(intArray, 1, 20);
        Array.setInt(intArray, 2, 30);

        // Printing the Array content
        System.out.println(Arrays.toString(intArray));
    }
}

Output
[10, 20, 30]

How to retrieve elements in an Array using java.lang.reflect.Array Class?

Like creating an array, retrieving elements in the array using reflect.Array Class is also different from the usual way. The process to retrieve elements in such an array is as follows: 

  • Get the index at which the element is to be retrieved.
  • To retrieve an element in an array (say of X class), use the getX() method of Array class, where X is to be replaced by the type of the array such as getInt(), getDouble(), etc. This method takes the X[] as the first parameter and the index at which the element is retrieved as the second parameter in the syntax below.

Syntax: 

Array.getX(X[], indexOfRetrieval);

Where X is to be replaced by the type of the array like int, double, etc.

  • This method retrieves the element at the specified index from this array.
  • Hence the required element has been retrieved from the array.

Below is an example to retrieve an element from an integer array using the Array class:

Example: To retrieve an element from an integer array: 

Java
// Java code to retrieve an element from an integer array,
// using the Array class:

import java.lang.reflect.Array;
import java.util.Arrays;

public class GfG {
    public static void main(String[] args)
    {

        // Get the size of the array
        int sizeOfArray = 3;

        // Create an integer array
        // using reflect.Array class
        // This is done using the newInstance() method
        int[] intArray = (int[])Array.newInstance(
            int.class, sizeOfArray);

        // Add elements to the array
        // This is done using the setInt() method
        Array.setInt(intArray, 0, 10);
        Array.setInt(intArray, 1, 20);
        Array.setInt(intArray, 2, 30);

        // Printing the Array content
        System.out.println(Arrays.toString(intArray));

        // Retrieve elements from the array
        // This is done using the getInt() method
        System.out.println("Element at index 0: "
                           + Array.getInt(intArray, 0));
        System.out.println("Element at index 1: "
                           + Array.getInt(intArray, 1));
        System.out.println("Element at index 2: "
                           + Array.getInt(intArray, 2));
    }
}

Output
[10, 20, 30]
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30


Previous Article
Next Article

Similar Reads

How to call private method from another class in Java with help of Reflection API?
We can call the private method of a class from another class in Java (which is defined using the private access modifier in Java). We can do this by changing the runtime behavior of the class by using some predefined methods of Java. For accessing private methods of different classes we will use Reflection API. To call the private method, we will u
3 min read
Reflection in Java
Reflection is an API that is used to examine or modify the behavior of methods, classes, and interfaces at runtime. The required classes for reflection are provided under java.lang.reflect package which is essential in order to understand reflection. So we are illustrating the package with visual aids to have a better understanding as follows: Refl
5 min read
How to Invoke Method by Name in Java Dynamically Using Reflection?
Java Reflection API provides us information about a Class to which the Object belongs to including the methods in this class. Using these Reflection API we would be able to get invoking pointer for a method in a class with its name. There are two functions used for this purpose: Invoking method with its nameFinding a method by Name in a class and i
4 min read
How to prevent Singleton Pattern from Reflection, Serialization and Cloning?
Prerequisite: Singleton Pattern In this article, we will see what various concepts can break the singleton property of a class and how to avoid them. There are mainly 3 concepts that can break the singleton property of a class. Let's discuss them one by one. Reflection: Reflection can be caused to destroy singleton property of the singleton class,
6 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.Class class in Java | Set 2
Java.lang.Class class in Java | Set 1 More methods: 1. int getModifiers() : This method returns the Java language modifiers for this class or interface, encoded in an integer. The modifiers consist of the Java Virtual Machine's constants for public, protected, private, final, static, abstract and interface. These modifiers are already decoded in Mo
15+ min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java.util.TimeZone Class (Set-2) | Example On TimeZone Class
TimeZone class (the methods of this class was discussed in this article Java.util.TimeZone Class | Set 1) can be used in many cases like using TimeZone class we can get the time difference in term of hour and minute between two places.Problem : How we can get time difference of time in terms of hours and minutes between two places of Earth?Solution
5 min read
Implement Pair Class with Unit Class in Java using JavaTuples
To implement a Pair class with a Unit class in Java using JavaTuples, you can use the Pair class provided by the library and create a new Unit class that extends the Unit class provided by the library. Here is an example implementation: Here is an example Java code that uses the MyPair class with MyUnit and displays the output: Java Code import org
4 min read
Implement Triplet Class with Pair Class in Java using JavaTuples
Following are the ways to implement Triplet Class with Pair Class Using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // create Pair Pair<Integer, String> pair = new Pair<Integer, String>( Integer.valueOf(1), "GeeksforGeeks"); // Print the Pair System.out.printl
2 min read
Implement Quintet Class with Quartet Class in Java using JavaTuples
Following are the ways to implement Quintet Class with Quartet Class Using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // create Quartet Quartet<String, String, String, String> quartet = new Quartet<String, String, String, String>( "Quartet", "Triplet
4 min read
Implement Quartet Class with Triplet Class in Java using JavaTuples
Following are the ways to implement Quartet Class with Triplet Class Using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // create Triplet Triplet<String, String, String> triplet = new Triplet<String, String, String>( "Triplet 1", "1", "GeeksforGe
3 min read
Implement Octet Class from Septet Class in Java using JavaTuples
Prerequisite: Octet Class, Septet Class Below are the methods to implement a Octet Class using Septet Class in Java: Using direct values // Java program to illustrate // implementing Octet Class // from Septet Class // using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // Create Sep
6 min read
Implement Ennead Class from Octet Class in Java using JavaTuples
Prerequisite: Ennead Class, Octet Class Below are the methods to implement a Ennead Class using Octet Class in Java: Using direct values // Java program to illustrate // implementing Ennead Class // from Octet Class // using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // Create Oct
7 min read
Implement Sextet Class from Quintet Class in Java using JavaTuples
Prerequisite: Sextet Class, Quintet Class Below are the methods to implement a Sextet Class using Quintet Class in Java: Using direct values // Java program to illustrate // implementing Sextet Class // from Quintet Class using // direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // crea
5 min read
Implement Septet Class from Sextet Class in Java using JavaTuples
Prerequisite: Septet Class, Sextet Class Below are the methods to implement a Septet Class using Sextet Class in Java: Using direct values // Java program to illustrate // implementing Septet Class // from Sextet Class // using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // Create
6 min read
Implement Decade Class from Ennead Class in Java using JavaTuples
Prerequisite: Decade Class, Ennead Class Below are the methods to implement a Decade Class using Ennead Class in Java: Using direct values // Java program to illustrate // implementing Decade Class // from Ennead Class // using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // Create
8 min read
Difference between Abstract Class and Concrete Class in Java
Abstract Class: An abstract class is a type of class in Java that is declared by the abstract keyword. An abstract class cannot be instantiated directly, i.e. the object of such class cannot be created directly using the new keyword. An abstract class can be instantiated either by a concrete subclass or by defining all the abstract method along wit
5 min read
Java - Inner Class vs Sub Class
Inner Class In Java, one can define a new class inside any other class. Such classes are known as Inner class. It is a non-static class, hence, it cannot define any static members in itself. Every instance has access to instance members of containing class. It is of three types: Nested Inner ClassMethod Local Inner ClassAnonymous Inner Class Genera
3 min read
Java I/O Operation - Wrapper Class vs Primitive Class Variables
It is better to use the Primitive Class variable for the I/O operation unless there is a necessity of using the Wrapper Class. In this article, we can discuss briefly both wrapper class and primitive data type. A primitive data type focuses on variable values, without any additional methods.The Default value of Primitive class variables are given b
3 min read
Using predefined class name as Class or Variable name in Java
In Java, you can use any valid identifier as a class or variable name. However, it is not recommended to use a predefined class name as a class or variable name in Java. The reason is that when you use a predefined class name as a class or variable name, you can potentially create confusion and make your code harder to read and understand. It may a
5 min read
Why BufferedReader class takes less time for I/O operation than Scanner class in java
In Java, both BufferReader and Scanner classes can be used for the reading inputs, but they differ in the performance due to their underlying implementations. The BufferReader class can be generally faster than the Scanner class because of the way it handles the input and parsing. This article will guide these difference, provide the detailed expla
3 min read
Java.io.ObjectInputStream Class in Java | Set 2
Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStream Class : defaultReadObject() : java.io.ObjectInpu
6 min read
Java.lang.StrictMath class in Java | Set 2
Java.lang.StrictMath Class in Java | Set 1More methods of java.lang.StrictMath class 13. exp() : java.lang.StrictMath.exp(double arg) method returns the Euler’s number raised to the power of double argument. Important cases: Result is NaN, if argument is NaN.Result is +ve infinity, if the argument is +ve infinity.Result is +ve zero, if argument is
6 min read
java.lang.instrument.ClassDefinition Class in Java
This class is used to bind together the supplied class and class file bytes in a single ClassDefinition object. These class provide methods to extract information about the type of class and class file bytes of an object. This class is a subclass of java.lang.Object class. Class declaration: public final class ClassDefinition extends ObjectConstruc
2 min read
java.net.URLConnection Class in Java
URLConnection Class in Java is an abstract class that represents a connection of a resource as specified by the corresponding URL. It is imported by the java.net package. The URLConnection class is utilized for serving two different yet related purposes, Firstly it provides control on interaction with a server(especially an HTTP server) than URL cl
5 min read
Java.util.GregorianCalendar Class in Java
Prerequisites : java.util.Locale, java.util.TimeZone, Calendar.get()GregorianCalendar is a concrete subclass(one which has implementation of all of its inherited members either from interface or abstract class) of a Calendar that implements the most widely used Gregorian Calendar with which we are familiar. java.util.GregorianCalendar vs java.util.
10 min read
java.lang.reflect.Proxy Class in Java
A proxy class is present in java.lang package. A proxy class has certain methods which are used for creating dynamic proxy classes and instances, and all the classes created by those methods act as subclasses for this proxy class. Class declaration: public class Proxy extends Object implements SerializableFields: protected InvocationHandler hIt han
4 min read
Java.util.concurrent.RecursiveAction class in Java with Examples
RecursiveAction is an abstract class encapsulates a task that does not return a result. It is a subclass of ForkJoinTask, which is an abstract class representing a task that can be executed on a separate core in a multicore system. The RecursiveAction class is extended to create a task that has a void return type. The code that represents the compu
3 min read
Java.util.concurrent.Phaser class in Java with Examples
Phaser's primary purpose is to enable synchronization of threads that represent one or more phases of activity. It lets us define a synchronization object that waits until a specific phase has been completed. It then advances to the next phase until that phase concludes. It can also be used to synchronize a single phase, and in that regard, it acts
7 min read