Wednesday 8 November 2017

How to get the class object of an array using Java Reflection | Reflection in java


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

ReflectionDemo1.java
/**
 * Obtaining the Class Object of an Array
 * 
 */
public class ReflectionDemo1
{
    public static void main(String[] args)
    {
        Class<String[]> stringArrayClassObj = String[].class;
        System.out.println(stringArrayClassObj);
        System.out.println(stringArrayClassObj.getName());
    }

}
Output
class [Ljava.lang.String;
[Ljava.lang.String;
ReflectionDemo2.java
/**
 * Obtaining the Class Object of an Array
 * 
 */
public class ReflectionDemo2
{
    public static void main(String[] args)
    {
        try
        {
            /*
             * The JVM represents an int via the letter I. The [ on the left
             * means it is the class of an int array I am interested in. This
             * works for all other primitives too
             */
            Class intArrayClassObj = Class.forName("[I");
            System.out.println(intArrayClassObj);
            System.out.println(intArrayClassObj.getName());

            System.out.println("------------------------------");

            /*
             * Notice the [L to the left of the class name, and the ; to the
             * right. This means an array of objects with the given type.
             */
            Class stringArrayClassObj = Class.forName("[Ljava.lang.String;");
            System.out.println(stringArrayClassObj);
            System.out.println(stringArrayClassObj.getName());
        }
        catch (ClassNotFoundException e)
        {
            e.printStackTrace();
        }

    }

}
Output
class [I
[I
------------------------------
class [Ljava.lang.String;
[Ljava.lang.String;
Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/ReflectionDemo_classObj_int_str_array.zip?attredirects=0&d=1

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

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/7b0b4fbacd011a10dc23b42c4acc3ae6988db782/BasicJava/ReflectionDemo_classObj_int_str_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