Wednesday 8 November 2017

How to create and access the array using Java Reflection | Reflection in java


Click here to watch in Youtube : 
https://www.youtube.com/watch?v=DkF-rbUcPRM&list=UUhwKlOVR041tngjerWxVccw

ReflectionDemo.java
import java.lang.reflect.Array;

/**
 * Creating Array and Accessing Array.
 * 
 */
public class ReflectionDemo
{
    public static void main(String[] args)
    {
        /*
         * Creating arrays via Java Reflection is done using the
         * java.lang.reflect.Array class
         * 
         * This code sample creates an array of int. The first parameter
         * int.class given to the Array.newInstance() method tells what type
         * each element in the array should be of. The second parameter states
         * how many elements the array should have space for.
         */
        int[] intArray = (int[]) Array.newInstance(int.class, 3);

        /*
         * It is possible to access the elements of an array using Java
         * Reflection. This is done via the Array.get(...) and Array.set(...)
         * methods.
         */
        Array.set(intArray, 0, 10);
        Array.set(intArray, 1, 20);
        Array.set(intArray, 2, 30);

        System.out.println("intArray[0] = " + Array.get(intArray, 0));
        System.out.println("intArray[1] = " + Array.get(intArray, 1));
        System.out.println("intArray[2] = " + Array.get(intArray, 2));

    }

}
Output
intArray[0] = 10
intArray[1] = 20
intArray[2] = 30

Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/ReflectionDemo_create_access_array.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/ReflectionDemo_create_access_array

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/7b0b4fbacd011a10dc23b42c4acc3ae6988db782/BasicJava/ReflectionDemo_create_access_array/?at=master

See also:
  • All JavaEE Videos Playlist
  • All JavaEE Videos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • No comments:

    Post a Comment