{"id":229,"date":"2021-01-21T17:27:02","date_gmt":"2021-01-21T17:27:02","guid":{"rendered":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/?page_id=229"},"modified":"2021-01-21T18:22:29","modified_gmt":"2021-01-21T18:22:29","slug":"reflection","status":"publish","type":"page","link":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/reflection\/","title":{"rendered":"Reflection"},"content":{"rendered":"<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_85 counter-hierarchy ez-toc-counter ez-toc-grey ez-toc-container-direction\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<label for=\"ez-toc-cssicon-toggle-item-6a6eb85306962\" class=\"ez-toc-cssicon-toggle-label\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #999;color:#999\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #999;color:#999\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/label><input type=\"checkbox\"  id=\"ez-toc-cssicon-toggle-item-6a6eb85306962\"  aria-label=\"Toggle\" \/><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/reflection\/#The_Class_Class\" >The Class Class<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/reflection\/#Examining_a_Class\" >Examining a Class<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/reflection\/#Array_Name_Encodings\" >Array Name Encodings<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/reflection\/#Creating_a_Class_Instance\" >Creating a Class Instance<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/reflection\/#The_Reflection_Classes\" >The Reflection Classes<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/reflection\/#Reconstructing_a_Class\" >Reconstructing a Class<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/reflection\/#Inspecting_a_Class_Instance\" >Inspecting a Class Instance<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/reflection\/#Instantiating_an_Object\" >Instantiating an Object<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/reflection\/#Creating_an_Array\" >Creating an Array<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/reflection\/#Calling_a_Method\" >Calling a Method<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/reflection\/#An_Example\" >An Example<\/a><ul class='ez-toc-list-level-5' ><li class='ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/reflection\/#Invoking_a_static_method\" >Invoking a static method<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/reflection\/#Invoking_an_instance_method\" >Invoking an instance method<\/a><\/li><\/ul><\/li><\/ul><\/li><\/ul><\/nav><\/div>\n\n<p class=\"wp-block-paragraph\">The Java Reflection API allows a program to inspect and discover information about classes and other elements of the program.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Reflection is used in Serialization and also in JavaBeans, among other applications.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The class&nbsp;<strong>java.lang.Class<\/strong>&nbsp;is the starting point for the reflection process.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The classes in the package&nbsp;<strong>java.lang.reflect<\/strong>&nbsp;provide more information for reflection, and are typically used in collaboration with the class&nbsp;<strong>Class<\/strong>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"The_Class_Class\"><\/span>The Class Class<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">There exists a class in Java called &#8212; appropriately, but perhaps confusingly &#8212; <strong>Class<\/strong>. This class maintains run-time type information about the components of your program while it is running.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Class&nbsp;<strong>Class<\/strong>&nbsp;does not have a public constructor. Instead, you obtain an instance of this class in one of a number of ways. For example, by using:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>the&nbsp;<strong>getClass()<\/strong>&nbsp;method in class&nbsp;Object<\/li><\/ul>\n\n\n\n<pre class=\"wp-block-preformatted\">String s;\n...\nClass c = s.getClass();<\/pre>\n\n\n\n<ul class=\"wp-block-list\"><li>the&nbsp;<strong>forName()<\/strong>&nbsp;method in class&nbsp;Class<\/li><\/ul>\n\n\n\n<pre class=\"wp-block-preformatted\">Class c = Class.forName(\"java.lang.String\");<\/pre>\n\n\n\n<ul class=\"wp-block-list\"><li>the&nbsp;<strong>class<\/strong>&nbsp;operator<\/li><\/ul>\n\n\n\n<pre class=\"wp-block-preformatted\">Class c1 = String.class;\nClass c2 = int.class;\nClass c3 = Double[].class;<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Class<\/strong>&nbsp;has many useful methods you can use to obtain information about the element it describes.&nbsp;<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, assume we have the following classes and interfaces:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage reflection;\n\npublic class Person\n{\n    public Person()\n    {\n    }\n    \n    public Person(String name, \n                  int age)\n    {\n        m_name = name;\n        m_age  = age;\n    }\n    \n    public void init(String name, \n                     int age)\n    {\n        m_name = name;\n        m_age  = age;\n    }\n\n    public String getName()\n    {\n        return m_name;\n    }\n    \n    public int getAge()\n    {\n        return m_age;\n    }\n    \n    \/\/\/\/\/\/\/ Data \/\/\/\/\/\/\/\/\n    private String  m_name;\n    private int     m_age;\n}\n<\/pre><\/div>\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage reflection;\n\npublic interface Firer\n{\n    public void fire(Employee emp);\n}\n<\/pre><\/div>\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage reflection;\n\npublic interface Hirer\n{\n    public void hire(Employee emp);\n}\n<\/pre><\/div>\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage reflection;\n\npublic interface HirerFirer\n    extends Hirer, Firer\n{\n}\n<\/pre><\/div>\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage reflection;\n\npublic class Employee\n    extends Person\n{\n    public Employee()\n    {\n    }\n    \n    public Employee(String name,   \n                    int  age, \n                    double salary, \n                    long id)\n    {\n        super(name, age);\n        m_salary = salary;\n        m_id = id;\n    }\n    \n    public void init(String name,   \n                     int age,\n                     double salary, \n                     long id)\n    {\n        super.init(name, age);\n        m_salary = salary;\n        m_id = id;\n    }\n    \n    public double getSalary()\n    {\n        return m_salary;\n    }\n    \n    public long getId()\n    {\n        return m_id;\n    }\n    \n    \/\/\/\/\/\/\/ Data \/\/\/\/\/\/\/\n    private double m_salary;\n    private long   m_id;\n}\n<\/pre><\/div>\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage reflection;\n\npublic class Manager\n    extends Employee\n    implements Hirer, Firer\n{\n    public Manager()\n    {\n    }\n    \n    public Manager(String name,   \n                   int  age,\n                   double salary, \n                   long id)\n    {\n        super(name, age, salary, id);\n    }\n    \n    public void hire(Employee emp)\n    {\n        \/\/ Details...\n    }\n\n    public void fire(Employee emp)\n    {\n        \/\/ Details...\n    }\n}\n<\/pre><\/div>\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Examining_a_Class\"><\/span>Examining a Class<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Given these classes and interfaces, here is an example that uses&nbsp;<strong>Class<\/strong>&nbsp;to obtain information about them:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage reflection;\n\npublic class ClassTestClass\n{\n    public static void main(String&#x5B;] args)\n    {\n        Class c;\n        try\n        {\n            c = Class.forName(&quot;java.lang.String&quot;);\n            printInfo(c);\n        }\n        catch(ClassNotFoundException e)\n        {\n            System.err.println(&quot;Class java.lang.String not found!&quot;);\n        }\n        c = int.class;\n        printInfo(c);\n        c = Double&#x5B;].class;\n        printInfo(c);\n        c = int&#x5B;].class;\n        printInfo(c);\n        short&#x5B;] shortArray = new short&#x5B;] {5, 10, 15};\n        c = shortArray.getClass();\n        printInfo(c);\n        c = Person.class;\n        printInfo(c);\n        c = Employee.class;\n        printInfo(c);\n        c = Manager.class;\n        printInfo(c);\n        c = Hirer.class;\n        printInfo(c);\n        c = HirerFirer.class;\n        printInfo(c);\n    }\n    \n    private static void printInfo(Class c)\n    {\n        System.out.println(&quot;toString(): &quot; + c.toString());\n        if (c.isPrimitive())\n            printPrimitiveInfo(c);\n        else if (c.isArray())\n            printArrayInfo(c);\n        else\n            printClassInfo(c);\n    }\n    \n    private static void printPrimitiveInfo(Class c)\n    {\n        String typeName = c.getName();\n        System.out.println(&quot;Type &quot; + typeName);\n    }\n    \n    private static void printArrayInfo(Class c)\n    {\n        Class component = c.getComponentType();\n        System.out.println(&quot;Array of &quot; + component.getName());\n    }\n    \n    private static void printClassInfo(Class c)\n    {\n        String className = c.getName();\n        int index = className.lastIndexOf(&#039;.&#039;);\n        String packageName;\n        if (index != -1)\n        {\n            packageName = className.substring(0, index);\n            System.out.println(&quot;package &quot; + packageName + &quot;;&quot;);\n            className = className.substring(index+1, className.length());\n        }\n\n        String type = (c.isInterface())?&quot;interface&quot;:&quot;class&quot;;\n        System.out.println(type + &quot; &quot; + className);\n\n        Class superClass = c.getSuperclass();\n        if (superClass != null)\n            System.out.println(&quot;    extends &quot; + superClass.getName());\n\n        Class&#x5B;] interfaces = c.getInterfaces();\n        if ((interfaces != null) &amp;&amp; (interfaces.length &gt; 0))\n        {\n            if (c.isInterface())\n                System.out.print(&quot;    extends &quot;);\n            else\n                System.out.print(&quot;    implements &quot;);\n            for (int i = 0; i &lt; interfaces.length; i++)\n            {\n                if (i &gt; 0)\n                    System.out.print(&quot;, &quot;);\n                System.out.print(interfaces&#x5B;i].getName());\n            }\n            System.out.println();\n        }\n\n        System.out.println(&quot;{&quot;);\n        System.out.println(&quot;}&quot;);\n    }\n}\n\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">This outputs the following (I&#8217;ve bolded the&nbsp;<strong>toString():<\/strong>&nbsp;line of each element output to make it easier to identify them visually):<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>toString(): class java.lang.String\n<\/strong>package java.lang;\nclass String\n    extends java.lang.Object\n    implements java.io.Serializable\n{\n}\n<strong>toString(): int\n<\/strong>Type int\n<strong>toString(): class [Ljava.lang.Double;\n<\/strong>Array of java.lang.Double\n<strong>toString(): class [I\n<\/strong>Array of int\n<strong>toString(): class [S\n<\/strong>Array of short\n<strong>toString(): class reflection.Person\n<\/strong>package reflection;\nclass Person\n    extends java.lang.Object\n{\n}\n<strong>toString(): class reflection.Employee\n<\/strong>package reflection;\nclass Employee\n    extends reflection.Person\n{\n}\n<strong>toString(): class reflection.Manager\n<\/strong>package reflection;\nclass Manager\n    extends reflection.Employee\n    implements reflection.Hirer, reflection.Firer\n{\n}\n<strong>toString(): interface reflection.Hirer\n<\/strong>package reflection;\ninterface Hirer\n{\n}\n<strong>toString(): interface reflection.HirerFirer\n<\/strong>package reflection;\ninterface HirerFirer\n    extends reflection.Hirer, reflection.Firer\n{\n}<\/pre>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Array_Name_Encodings\"><\/span>Array Name Encodings<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Note the strange output for arrays.&nbsp; In the case of an array, the&nbsp;<strong>toString()<\/strong>&nbsp;method (and the&nbsp;<strong>getName()<\/strong>&nbsp;method) for&nbsp;<strong>Class<\/strong>&nbsp;returns a name like:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>[Ljava.lang.Double;<\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Where the&nbsp;<strong>[<\/strong>&nbsp;means &#8220;array of&#8221; and the remaining character(s) are chosen from the following table (see the&nbsp;<a href=\"http:\/\/java.sun.com\/docs\/books\/jls\/html\/javalang.doc2.html\" target=\"_blank\" rel=\"noreferrer noopener\">Java Language Specification<\/a>), with the specified meaning.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>B<\/strong><\/td><td><strong>byte<\/strong><\/td><\/tr><tr><td><strong>C<\/strong><\/td><td><strong>char<\/strong><\/td><\/tr><tr><td><strong>D<\/strong><\/td><td><strong>double<\/strong><\/td><\/tr><tr><td><strong>F<\/strong><\/td><td><strong>float<\/strong><\/td><\/tr><tr><td><strong>I<\/strong><\/td><td><strong>int<\/strong><\/td><\/tr><tr><td><strong>J<\/strong><\/td><td><strong>long<\/strong><\/td><\/tr><tr><td><strong>L<\/strong><\/td><td><strong>class or interface<\/strong><\/td><\/tr><tr><td><strong>S<\/strong><\/td><td><strong>short<\/strong><\/td><\/tr><tr><td><strong>Z<\/strong><\/td><td><strong>boolean<\/strong><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">For example, the following piece of code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>(new int&#91;3]&#91;4]&#91;5]&#91;6]&#91;7]&#91;8]&#91;9]).getClass().getName()<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">returns:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;&#91;&#91;&#91;&#91;&#91;&#91;I<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This strange encoding is used in a number of places in Java, notably in Reflection and also in JNI (Java Native Interface) when interfacing with code written in other languages (notably C and C++).<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Creating_a_Class_Instance\"><\/span>Creating a Class Instance<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">You can use the&nbsp;<strong>Class<\/strong>&nbsp;class to create a new instance of a specified class, by calling its&nbsp;<strong>newInstance()<\/strong>&nbsp;method:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; highlight: [9,10,11,12,13,14,15,16,17]; title: ; quick-code: false; notranslate\" title=\"\">\npackage reflection;\n\npublic class NewInstanceTest\n{\n    public static void main(String&#x5B;] args)\n    {\n        try\n        {\n            Class empClass = Employee.class;\n            Employee emp = (Employee) empClass.newInstance();\n            emp.init(&quot;Eugene McCracken&quot;, 34, 45000, 45678);\n            System.out.println(&quot;Name: &quot; + emp.getName());\n            \n            Class mgrClass = Class.forName(&quot;reflection.Manager&quot;);\n            Manager mgr = (Manager) mgrClass.newInstance();\n            mgr.init(&quot;Pietro Botticelli&quot;, 385, 50000000, 675978);\n            System.out.println(&quot;Name: &quot; + mgr.getName());\n        }\n        catch(ClassNotFoundException e)\n        {\n            System.err.println(&quot;Class not found&quot;);\n        }\n        catch(InstantiationException e)\n        {\n            System.err.println(&quot;Failed to instantiate&quot;);\n        }\n        catch(IllegalAccessException e)\n        {\n            System.err.println(&quot;Unable to access class&quot;);\n        }\n    }\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">which produces the following output:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Name: Eugene McCracken\nName: Pietro Botticelli<\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The first created instance used a mechanism that depends on the class already having been loaded into the JVM.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The second created instance used the <strong>forName()<\/strong> method, which allows you to explicitly load a class (using its fully qualified name) before instantiating it.&nbsp; The only requirement here is that the class must exist in the class path.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"The_Reflection_Classes\"><\/span>The Reflection Classes<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The package&nbsp;<strong>java.lang.reflect<\/strong>&nbsp;contains a number of classes to supplement the information that&nbsp;<strong>Class<\/strong>&nbsp;can provide:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Constructor<\/strong>&nbsp;&#8212; describes a constructor for a class<\/li><li><strong>Field<\/strong>&nbsp;&#8212; describes a data field for a class<\/li><li><strong>Method<\/strong>&nbsp;&#8212; describes a method for a class<\/li><li><strong>Modifier<\/strong>&nbsp;&#8212; describes what modifiers (static,&nbsp;final,&nbsp;abstract, etc.) associated with an element.<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">In addition,&nbsp;<strong>java.lang.reflect<\/strong>&nbsp;contains an interface:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Member<\/strong><\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">All reflection classes that represent a class member (<strong>Constructor<\/strong>, <strong>Field<\/strong>, <strong>Method<\/strong>) implement this interface.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Reconstructing_a_Class\"><\/span>Reconstructing a Class<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s an example of how we can reconstruct a class using reflection. This program is a modification of the eariler program that used just the class&nbsp;<strong>Class<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">First, for purposes of exposition, I&#8217;ve added another class which adds additional features to be reconstructed:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage reflection;\n\n\/* package private *\/ class Company\n    implements HirerFirer\n{\n    public Company()\n    {\n    }\n    \n    public Company(String name, int maxEmps)\n    {\n        m_name = name;\n        m_employees = new Employee&#x5B;maxEmps];\n    }\n    \n    public void init(String name, int maxEmps)\n    {\n        m_name = name;\n        m_employees = new Employee&#x5B;maxEmps];\n    }\n    \n    public void hire(Employee emp)\n    {\n        m_employees&#x5B;m_lastIndex++] = emp;\n          \/\/ Will throw an exception if index out of bounds\n        m_empCount++;\n    }\n    \n    public void fire(Employee emp)\n    {\n        \/\/ Search for emp, and if found remove reference\n        for (int i = 0; i &lt; m_lastIndex; i++)\n        {\n            if (m_employees&#x5B;i] == emp)\n            {\n                m_employees&#x5B;i] = null;\n                if (i == m_lastIndex)\n                    m_lastIndex--;\n                m_empCount--;\n                return;\n            }\n        }\n    }\n    \n    public Employee&#x5B;] getEmployees()\n    {\n        return m_employees;\n    }\n    \n    public void setEmployees(Employee&#x5B;] emps)\n    {\n        m_employees = emps;\n    }\n    \n    \/\/\/\/ Data \/\/\/\/\n    private String      m_name;\n    private Employee&#x5B;]  m_employees;\n    private int         m_empCount = 0;\n    private int         m_lastIndex = 0;\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">So here&#8217;s the example program that reconstructs a class using reflection:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage reflection;\n\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Member;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Modifier;\n\npublic class ClassTestClass2\n{\n    public static void main(String&#x5B;] args)\n    {\n        Class c;\n        try\n        {\n            c = Class.forName(&quot;java.lang.String&quot;);\n            printInfo(c);\n        }\n        catch(ClassNotFoundException e)\n        {\n            System.err.println(&quot;Class java.lang.String not found!&quot;);\n        }\n        c = int.class;\n        printInfo(c);\n        c = Double&#x5B;].class;\n        printInfo(c);\n        c = int&#x5B;].class;\n        printInfo(c);\n        short&#x5B;] shortArray = new short&#x5B;] {5, 10, 15};\n        c = shortArray.getClass();\n        printInfo(c);\n        c = Person.class;\n        printInfo(c);\n        c = Employee.class;\n        printInfo(c);\n        c = Manager.class;\n        printInfo(c);\n        c = Hirer.class;\n        printInfo(c);\n        c = HirerFirer.class;\n        printInfo(c);\n        c = Company.class;\n        printInfo(c);\n        c = ClassTestClass2.class;\n        printInfo(c);\n    }\n    \n    private static void printInfo(Class c)\n    {\n        System.out.println(&quot;---- toString(): &quot; + \n                           c.toString() + &quot; ----&quot;);\n        if (c.isPrimitive())\n            printPrimitiveInfo(c);\n        else if (c.isArray())\n            printArrayInfo(c);\n        else if (c.isInterface())\n            printInterfaceInfo(c);\n        else\n            printClassInfo(c);\n    }\n    \n    private static void printPrimitiveInfo(Class c)\n    {\n        String typeName = c.getName();\n        System.out.println(&quot;Type &quot; + typeName);\n    }\n    \n    private static void printArrayInfo(Class c)\n    {\n        Class component = c.getComponentType();\n        System.out.println(&quot;Array of &quot; + component.getName());\n    }\n    \n    private static String&#x5B;] getPackageAndName(String name)\n    {\n        int index = name.lastIndexOf(&#039;.&#039;);\n        String packageName = null;\n        if (index != -1)\n        {\n            packageName = name.substring(0, index);\n            name = name.substring(index+1, name.length());\n        }\n        \n        return new String&#x5B;] { packageName, name };\n    }\n    \n    private static void printClassInfo(Class c)\n    {\n        String&#x5B;] names = getPackageAndName(c.getName());\n        String packageName = names&#x5B;0];\n        String className = names&#x5B;1];\n\n        if (packageName != null)\n            System.out.println(&quot;package &quot; + packageName + &quot;;&quot;);\n        \n        int mods = c.getModifiers();\n        System.out.println(Modifier.toString(mods) + \n                           &quot; class &quot; + className);\n\n        Class superClass = c.getSuperclass();\n        if (superClass != null)\n            System.out.println(INDENT + INDENT + \n                               &quot;extends &quot; + superClass.getName());\n\n        Class&#x5B;] interfaces = c.getInterfaces();\n        if ((interfaces != null) &amp;&amp; (interfaces.length &gt; 0))\n        {\n            System.out.print(INDENT + INDENT + &quot;implements &quot;);\n            for (int i = 0; i &lt; interfaces.length; i++)\n            {\n                if (i &gt; 0)\n                    System.out.print(&quot;, &quot;);\n                System.out.print(interfaces&#x5B;i].getName());\n            }\n            System.out.println();\n        }\n\n        System.out.println(&quot;{&quot;);\n        printMembers(c);\n        System.out.println(&quot;}&quot;);\n    }\n\n    private static void printInterfaceInfo(Class c)\n    {\n        String&#x5B;] names = getPackageAndName(c.getName());\n        String packageName = names&#x5B;0];\n        String className = names&#x5B;1];\n\n        if (packageName != null)\n            System.out.println(&quot;package &quot; + packageName + &quot;;&quot;);\n        \n        int mods = c.getModifiers();\n        System.out.println(Modifier.toString(mods) + \n                           &quot; interface &quot; + className);\n\n        Class&#x5B;] interfaces = c.getInterfaces();\n        if ((interfaces != null) &amp;&amp; (interfaces.length &gt; 0))\n        {\n            System.out.print(INDENT + INDENT + &quot;extends &quot;);\n            for (int i = 0; i &lt; interfaces.length; i++)\n            {\n                if (i &gt; 0)\n                    System.out.print(&quot;, &quot;);\n                System.out.print(interfaces&#x5B;i].getName());\n            }\n            System.out.println();\n        }\n\n        System.out.println(&quot;{&quot;);\n        printMembers(c);\n        System.out.println(&quot;}&quot;);\n    }\n    \n    private static void printMembers(Class c)\n    {\n        printConstructors(c);\n        printMethods(c);\n        printFields(c);\n    }\n    \n    private static void printConstructors(Class c)\n    {\n        Constructor&#x5B;] constructors = c.getDeclaredConstructors();\n        for (int i = 0; i &lt; constructors.length; i++)\n        {\n            if (i == 0)\n                System.out.println(INDENT + &quot;\/\/ Constructors&quot;);\n            Constructor con = constructors&#x5B;i];\n            \n            \/\/ Strip off package name from constructor name\n            String&#x5B;] names = getPackageAndName(con.getName());\n            String conName = names&#x5B;1];\n            int mods = con.getModifiers();\n            System.out.print(INDENT + Modifier.toString(mods));\n            System.out.print(&quot; &quot; + conName);\n            \n            Class&#x5B;] params = con.getParameterTypes();\n            printParams(params);\n            if (c.isInterface())\n                System.out.println(&quot;;&quot;);\n            else\n            {\n                System.out.println(&quot; { &quot; + \n                                   UNKNOWN_IMPLEMENTATION + \n                                   &quot; }&quot;);\n            }\n        }\n    }\n\n    private static void printMethods(Class c)\n    {\n        Method&#x5B;] methods = c.getDeclaredMethods();\n        for (int i = 0; i &lt; methods.length; i++)\n        {\n            if (i == 0)\n                System.out.println(INDENT + &quot;\/\/ Methods&quot;);\n            Method method = methods&#x5B;i];\n            int mods = method.getModifiers();\n            System.out.print(INDENT + Modifier.toString(mods));\n            Class retType = method.getReturnType();\n            System.out.print(&quot; &quot; + getArrayType(retType) + &quot; &quot; +\n                             method.getName() );\n            \n            Class&#x5B;] params = method.getParameterTypes();\n            printParams(params);\n            if (c.isInterface())\n                System.out.println(&quot;;&quot;);\n            else\n                System.out.println(&quot; { &quot; + \n                                   UNKNOWN_IMPLEMENTATION + \n                                   &quot; }&quot;);\n        }\n    }\n    \n    private static void printParams(Class&#x5B;] params)\n    {\n        System.out.print(&quot;(&quot;);\n        for (int i = 0; i &lt; params.length; i++)\n        {\n            if (i &gt; 0)\n                System.out.print(&quot;, &quot;);\n            System.out.print(getArrayType(params&#x5B;i]) + \n                             &quot; p&quot; + (i+1));\n        }\n        System.out.print(&quot;)&quot;);\n    }\n    \n    private static void printFields(Class c)\n    {\n        Field&#x5B;] fields = c.getDeclaredFields();\n        for (int i = 0; i &lt; fields.length; i++)\n        {\n            if (i == 0)\n                System.out.println(INDENT + &quot;\/\/ Fields&quot;);\n            Field field = fields&#x5B;i];\n            int mods = field.getModifiers();\n            System.out.print(INDENT + Modifier.toString(mods));\n            Class type = field.getType();\n            System.out.println(&quot; &quot; + getArrayType(type) + \n                               &quot; &quot; + field.getName() + &quot;;&quot;);\n        }\n    }\n    \n    private static String getArrayType(Class c)\n    {\n        if (!c.isArray())\n            return c.getName();\n        else\n        {\n            \/\/ Use recursion to construct proper string\n            String type = getArrayType(c.getComponentType());\n            return type + &quot;&#x5B;]&quot;;\n        }\n    }\n    \n    private static final String UNKNOWN_IMPLEMENTATION = &quot;\/* ??? *\/&quot;;\n    private static final String INDENT = &quot;  &quot;;\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">The program isn&#8217;t quite complete, since it does not handle the following features:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Full&nbsp;<strong>throws<\/strong>&nbsp;specifications for constructors and methods<\/li><li>Nested and inner classes<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Adding support for these features (and others?) is left as an exercise for the reader.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The above program produces the following output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>---- toString(): class java.lang.String ----\npackage java.lang;\npublic final synchronized class String\n    extends java.lang.Object\n    implements java.io.Serializable\n{\n  \/\/ Constructors\n  public String() { \/* ??? *\/ }\n  public String(java.lang.String p1) { \/* ??? *\/ }\n  public String(char&#91;] p1) { \/* ??? *\/ }\n  public String(char&#91;] p1, int p2, int p3) { \/* ??? *\/ }\n  public String(byte&#91;] p1, int p2, int p3, int p4) { \/* ??? *\/ }\n  public String(byte&#91;] p1, int p2) { \/* ??? *\/ }\n  private String(byte&#91;] p1, int p2, int p3, sun.io.ByteToCharConverter p4) { \/* ??? *\/ }\n  public String(byte&#91;] p1, int p2, int p3, java.lang.String p4) { \/* ??? *\/ }\n  public String(byte&#91;] p1, java.lang.String p2) { \/* ??? *\/ }\n  public String(byte&#91;] p1, int p2, int p3) { \/* ??? *\/ }\n  public String(byte&#91;] p1) { \/* ??? *\/ }\n  public String(java.lang.StringBuffer p1) { \/* ??? *\/ }\n  private String(int p1, int p2, char&#91;] p3) { \/* ??? *\/ }\n  \/\/ Methods\n  public int length() { \/* ??? *\/ }\n  public char charAt(int p1) { \/* ??? *\/ }\n  public void getChars(int p1, int p2, char&#91;] p3, int p4) { \/* ??? *\/ }\n  public void getBytes(int p1, int p2, byte&#91;] p3, int p4) { \/* ??? *\/ }\n  private byte&#91;] getBytes(sun.io.CharToByteConverter p1) { \/* ??? *\/ }\n  public byte&#91;] getBytes(java.lang.String p1) { \/* ??? *\/ }\n  public byte&#91;] getBytes() { \/* ??? *\/ }\n  public boolean equals(java.lang.Object p1) { \/* ??? *\/ }\n  public boolean equalsIgnoreCase(java.lang.String p1) { \/* ??? *\/ }\n  public int compareTo(java.lang.String p1) { \/* ??? *\/ }\n  public boolean regionMatches(int p1, java.lang.String p2, int p3, int p4) { \/* ??? *\/ }\n  public boolean regionMatches(boolean p1, int p2, java.lang.String p3, int p4, int p5) { \/* ??? *\/ }\n  public boolean startsWith(java.lang.String p1, int p2) { \/* ??? *\/ }\n  public boolean startsWith(java.lang.String p1) { \/* ??? *\/ }\n  public boolean endsWith(java.lang.String p1) { \/* ??? *\/ }\n  public int hashCode() { \/* ??? *\/ }\n  public int indexOf(int p1) { \/* ??? *\/ }\n  public int indexOf(int p1, int p2) { \/* ??? *\/ }\n  public int lastIndexOf(int p1) { \/* ??? *\/ }\n  public int lastIndexOf(int p1, int p2) { \/* ??? *\/ }\n  public int indexOf(java.lang.String p1) { \/* ??? *\/ }\n  public int indexOf(java.lang.String p1, int p2) { \/* ??? *\/ }\n  public int lastIndexOf(java.lang.String p1) { \/* ??? *\/ }\n  public int lastIndexOf(java.lang.String p1, int p2) { \/* ??? *\/ }\n  public java.lang.String substring(int p1) { \/* ??? *\/ }\n  public java.lang.String substring(int p1, int p2) { \/* ??? *\/ }\n  public java.lang.String concat(java.lang.String p1) { \/* ??? *\/ }\n  public java.lang.String replace(char p1, char p2) { \/* ??? *\/ }\n  public java.lang.String toLowerCase(java.util.Locale p1) { \/* ??? *\/ }\n  public java.lang.String toLowerCase() { \/* ??? *\/ }\n  public java.lang.String toUpperCase(java.util.Locale p1) { \/* ??? *\/ }\n  public java.lang.String toUpperCase() { \/* ??? *\/ }\n  public java.lang.String trim() { \/* ??? *\/ }\n  public java.lang.String toString() { \/* ??? *\/ }\n  public char&#91;] toCharArray() { \/* ??? *\/ }\n  public static java.lang.String valueOf(java.lang.Object p1) { \/* ??? *\/ }\n  public static java.lang.String valueOf(char&#91;] p1) { \/* ??? *\/ }\n  public static java.lang.String valueOf(char&#91;] p1, int p2, int p3) { \/* ??? *\/ }\n  public static java.lang.String copyValueOf(char&#91;] p1, int p2, int p3) { \/* ??? *\/ }\n  public static java.lang.String copyValueOf(char&#91;] p1) { \/* ??? *\/ }\n  public static java.lang.String valueOf(boolean p1) { \/* ??? *\/ }\n  public static java.lang.String valueOf(char p1) { \/* ??? *\/ }\n  public static java.lang.String valueOf(int p1) { \/* ??? *\/ }\n  public static java.lang.String valueOf(long p1) { \/* ??? *\/ }\n  public static java.lang.String valueOf(float p1) { \/* ??? *\/ }\n  public static java.lang.String valueOf(double p1) { \/* ??? *\/ }\n  public native java.lang.String intern() { \/* ??? *\/ }\n   int utfLength() { \/* ??? *\/ }\n  \/\/ Fields\n  private char&#91;] value;\n  private int offset;\n  private int count;\n  private static final long serialVersionUID;\n}\n---- toString(): int ----\nType int\n---- toString(): class &#91;Ljava.lang.Double; ----\nArray of java.lang.Double\n---- toString(): class &#91;I ----\nArray of int\n---- toString(): class &#91;S ----\nArray of short\n---- toString(): class reflection.Person ----\npackage reflection;\npublic synchronized class Person\n    extends java.lang.Object\n{\n  \/\/ Constructors\n  public Person() { \/* ??? *\/ }\n  public Person(java.lang.String p1, int p2) { \/* ??? *\/ }\n  \/\/ Methods\n  public int getAge() { \/* ??? *\/ }\n  public java.lang.String getName() { \/* ??? *\/ }\n  public void init(java.lang.String p1, int p2) { \/* ??? *\/ }\n  \/\/ Fields\n  private java.lang.String m_name;\n  private int m_age;\n}\n---- toString(): class reflection.Employee ----\npackage reflection;\npublic synchronized class Employee\n    extends reflection.Person\n{\n  \/\/ Constructors\n  public Employee() { \/* ??? *\/ }\n  public Employee(java.lang.String p1, int p2, double p3, long p4) { \/* ??? *\/ }\n  \/\/ Methods\n  public long getId() { \/* ??? *\/ }\n  public double getSalary() { \/* ??? *\/ }\n  public void init(java.lang.String p1, int p2, double p3, long p4) { \/* ??? *\/ }\n  \/\/ Fields\n  private double m_salary;\n  private long m_id;\n}\n---- toString(): class reflection.Manager ----\npackage reflection;\npublic synchronized class Manager\n    extends reflection.Employee\n    implements reflection.Hirer, reflection.Firer\n{\n  \/\/ Constructors\n  public Manager() { \/* ??? *\/ }\n  public Manager(java.lang.String p1, int p2, double p3, long p4) { \/* ??? *\/ }\n  \/\/ Methods\n  public void fire(reflection.Employee p1) { \/* ??? *\/ }\n  public void hire(reflection.Employee p1) { \/* ??? *\/ }\n}\n---- toString(): interface reflection.Hirer ----\npackage reflection;\npublic abstract interface interface Hirer\n{\n  \/\/ Methods\n  public abstract void hire(reflection.Employee p1);\n}\n---- toString(): interface reflection.HirerFirer ----\npackage reflection;\npublic interface interface HirerFirer\n    extends reflection.Hirer, reflection.Firer\n{\n}\n---- toString(): class reflection.Company ----\npackage reflection;\nsynchronized class Company\n    extends java.lang.Object\n    implements reflection.HirerFirer\n{\n  \/\/ Constructors\n  public Company() { \/* ??? *\/ }\n  public Company(java.lang.String p1, int p2) { \/* ??? *\/ }\n  \/\/ Methods\n  public void fire(reflection.Employee p1) { \/* ??? *\/ }\n  public reflection.Employee&#91;] getEmployees() { \/* ??? *\/ }\n  public void hire(reflection.Employee p1) { \/* ??? *\/ }\n  public void init(java.lang.String p1, int p2) { \/* ??? *\/ }\n  public void setEmployees(reflection.Employee&#91;] p1) { \/* ??? *\/ }\n  \/\/ Fields\n  private java.lang.String m_name;\n  private reflection.Employee&#91;] m_employees;\n  private int m_empCount;\n  private int m_lastIndex;\n}\n---- toString(): class reflection.ClassTestClass2 ----\npackage reflection;\npublic synchronized class ClassTestClass2\n    extends java.lang.Object\n{\n  \/\/ Constructors\n  public ClassTestClass2() { \/* ??? *\/ }\n  \/\/ Methods\n  private static java.lang.String getArrayType(java.lang.Class p1) { \/* ??? *\/ }\n  private static java.lang.String&#91;] getPackageAndName(java.lang.String p1) { \/* ??? *\/ }\n  public static void main(java.lang.String&#91;] p1) { \/* ??? *\/ }\n  private static void printArrayInfo(java.lang.Class p1) { \/* ??? *\/ }\n  private static void printClassInfo(java.lang.Class p1) { \/* ??? *\/ }\n  private static void printConstructors(java.lang.Class p1) { \/* ??? *\/ }\n  private static void printFields(java.lang.Class p1) { \/* ??? *\/ }\n  private static void printInfo(java.lang.Class p1) { \/* ??? *\/ }\n  private static void printInterfaceInfo(java.lang.Class p1) { \/* ??? *\/ }\n  private static void printMembers(java.lang.Class p1) { \/* ??? *\/ }\n  private static void printMethods(java.lang.Class p1) { \/* ??? *\/ }\n  private static void printParams(java.lang.Class&#91;] p1) { \/* ??? *\/ }\n  private static void printPrimitiveInfo(java.lang.Class p1) { \/* ??? *\/ }\n  static java.lang.Class class$(java.lang.String p1) { \/* ??? *\/ }\n  \/\/ Fields\n  private static final java.lang.String UNKNOWN_IMPLEMENTATION;\n  private static final java.lang.String INDENT;\n  static java.lang.Class array$Ljava$lang$Double;\n  static java.lang.Class array$I;\n  static java.lang.Class class$reflection$Person;\n  static java.lang.Class class$reflection$Employee;\n  static java.lang.Class class$reflection$Manager;\n  static java.lang.Class class$reflection$Hirer;\n  static java.lang.Class class$reflection$HirerFirer;\n  static java.lang.Class class$reflection$Company;\n  static java.lang.Class class$reflection$ClassTestClass2;\n}<\/code><\/pre>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\"><p>Note, in particular, the output for the class&nbsp;<strong>ClassTestClass2<\/strong>&nbsp;itself is a little strange; it appears to have some extra static fields with strange names.<\/p><\/blockquote>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Inspecting_a_Class_Instance\"><\/span>Inspecting a Class Instance<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Horstmann and Cornell, in&nbsp;<em><strong>CORE Java, Volume I : Fundamentals<\/strong><\/em>, create a useful little class,&nbsp;<strong>ObjectAnalyzer<\/strong>, that allows you to peek into class instances at run time to determine their internal state. This could be useful for debugging, etc.&nbsp;<strong>ObjectAnalyzer<\/strong>&nbsp;is a class that has only static methods; it is non-instantiatable.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here is a version modified to work under JDK 1.1 and beyond. It has also been enhanced to output information about arrays as well as classes:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage reflection;\n\nimport java.lang.reflect.Array;\nimport java.lang.reflect.Field;\n\n\n\/**\n*   This class allows the programmer to peek into\n*   a specified class, and also to provide a generic\n*   equals() mechanism.\n*\n*   @author Horstmann &amp; Cornell, CORE Java 1.2, Vol I, p214\n*   @author Bryan J. Higgs, modified &amp; extended 29 Dec 1999\n*\/\npublic class ObjectAnalyzer\n{\n    private ObjectAnalyzer()\n    {\n        \/\/ Prevent instantiation\n    }\n    \n    public static String toString(Object obj)\n    {\n        return toString(obj, 0);\n    }\n    \n    private static String toString(Object obj, \n                                   int indentLevel)\n    {\n        String indent = &quot;&quot;;\n        for (int i = 0; i &lt; indentLevel; i++)\n            indent += &quot; &quot;;\n            \n        Class c = obj.getClass();\n        if (c.isArray())\n        {\n            Class type = c.getComponentType();\n            String typeString = type.getName();\n            if (type.isArray())\n                typeString = getArrayType(type);\n                \n            return indent + &quot;Array of &quot; + typeString + &quot;\\n&quot; +\n                   getArrayContents(obj, indentLevel);\n        }\n            \n        String r = indent + c.getName();\n        Class sc = c.getSuperclass();\n        if (sc != null &amp;&amp; !sc.equals(Object.class))\n            r += &quot; extends &quot; + sc;\n        r += &quot;\\n&quot;;\n        Field&#x5B;] fields = c.getDeclaredFields();\n        for (int i = 0; i &lt; fields.length; i++)\n        {\n            Field field = fields&#x5B;i];\n            r += field.getName() + &quot;=&quot;;\n            String s = &quot;???&quot;;\/\/ Expect access problems\n            try\n            {\n                Object value = field.get(obj);\n                Class vc = value.getClass();\n                if (!vc.isArray())\n                    s = value.toString();\n                else\n                {\n                    s = &quot;\\n&quot;;\n                    s += getArrayContents(value, \n                                          indentLevel + 1);\n                }\n            }\n            catch(NullPointerException e)\n            {\n                s = &quot;null&quot;;\n            }\n            catch(IllegalAccessException e)\n            {}\n            r += s;\n            if (!r.endsWith(&quot;\\n&quot;))\n                r += &quot;\\n&quot;;\n        }\n        return r;\n    }\n    \n    private static String getArrayContents(Object obj, \n                                           int indentLevel)\n    {\n        String indent = &quot;&quot;;\n        for (int i = 0; i &lt; indentLevel; i++)\n            indent += &quot; &quot;;\n            \n        Class c = obj.getClass();\n        String r = &quot;&quot;;\n        int length = Array.getLength(obj);\n        for (int i = 0; i &lt; length; i++)\n        {\n            r += indent + &quot;&#x5B;&quot; + i + &quot;]=&quot;;\n            String s = &quot;???&quot;;\/\/ Expect access problems\n            try\n            {\n                Object value = Array.get(obj, i);\n                Class vc = value.getClass();\n                s = &quot;(&quot; + getArrayType(vc) + &quot;)&quot;;\n                if (!vc.isArray())\n                {\n                    s += value.toString();\n                }\n                else\n                {\n                    s += &quot;\\n&quot; + \n                         getArrayContents(value, \n                                          indentLevel + 1);\n                }\n                \n            }\n            catch(NullPointerException e)\n            {\n                s = &quot;null&quot;;\n            }\n            r += s;\n            if (!r.endsWith(&quot;\\n&quot;))\n                r += &quot;\\n&quot;;\n        }\n        return r;\n    }\n    \n    private static String getArrayType(Class c)\n    {\n        if (!c.isArray())\n            return c.getName();\n        else\n        {\n            \/\/ Use recursion to construct proper string\n            String type = getArrayType(c.getComponentType());\n            return type + &quot;&#x5B;]&quot;;\n        }\n    }\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Here is a small test program to exercise it:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage reflection;\n\nimport java.util.Date;\nimport java.util.Vector;\n\npublic class ObjectAnalyzerTest\n{\n    public static void main(String&#x5B;] args)\n    {\n        String&#x5B;] strings = new String&#x5B;] {&quot;Fred&quot;, &quot;Joe&quot;, &quot;Martha&quot;};\n        System.out.println(&quot;strings: &quot; + \n                           ObjectAnalyzer.toString(strings));\n        \n        System.out.println(&quot;System.out: &quot; + \n                           ObjectAnalyzer.toString(System.out));\n        \n        Person&#x5B;] parents = new Person&#x5B;] \n        { \n            new Person(&quot;Vernon Clydesdale&quot;, 48), null\n        };\n        Person person = \n             new Person(&quot;Myrtle A. Fibbertigibbet&quot;, 24, parents);\n        System.out.println(&quot;Person: &quot; + \n                           ObjectAnalyzer.toString(person));\n        \n        Object&#x5B;] objects = new Object&#x5B;]\n        {\n            &quot;I am a String&quot;, new Person(&quot;Lionel Barksdale&quot;, 54),\n            new Object&#x5B;]\n            {\n                &quot;Another String&quot;, new Long(45L), new Vector(),\n            },\n            new Double(83.4), new Date()\n        };\n        System.out.println(&quot;objects: &quot; + \n                           ObjectAnalyzer.toString(objects));\n    }\n    \n    \/\/\/\/ Nested class for testing \/\/\/\/\n    static class Person\n    {\n        Person(String name, int age)\n        {\n            this(name, age, null);\n        }\n        \n        Person(String name, int age, Person&#x5B;] parents)\n        {\n            m_name = name;\n            m_age  = age;\n            m_parents = parents;\n            m_count++;\n        }\n        \n        public String toString()\n        {\n            return m_name;\n        }\n        \n        \/\/\/\/\/ Data \/\/\/\/\n        String      m_name;\n        int         m_age;\n        static int  m_count = 0;\n        Person&#x5B;]    m_parents;\n    }\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">This outputs the following:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>strings: Array of java.lang.String\n[0]=(java.lang.String)Fred\n[1]=(java.lang.String)Joe\n[2]=(java.lang.String)Martha\n\nSystem.out: java.io.PrintStream extends class java.io.FilterOutputStream\nautoFlush=???\ntrouble=???\ntextOut=???\ncharOut=???\nclosing=???\n\nPerson: reflection.ObjectAnalyzerTest$Person\nm_name=Myrtle A. Fibbertigibbet\nm_age=24\nm_count=2\nm_parents=\n [0]=(reflection.ObjectAnalyzerTest$Person)Vernon Clydesdale\n [1]=null\n\nobjects: Array of java.lang.Object\n[0]=(java.lang.String)I am a String\n[1]=(reflection.ObjectAnalyzerTest$Person)Lionel Barksdale\n[2]=(java.lang.Object[])\n [0]=(java.lang.String)Another String\n [1]=(java.lang.Long)45\n [2]=(java.util.Vector)[]\n[3]=(java.lang.Double)83.4\n[4]=(java.util.Date)Wed Dec 29 16:51:09 EST 1999<\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Note that the program cannot output the contents of the private fields in&nbsp;<strong>System.out<\/strong>, because Java&#8217;s access control won&#8217;t allow it. In JDK 1.2, however, they have added the ability to override the access control, subject to&nbsp;<strong>SecurityManager<\/strong>&#8216;s approval.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s a version of the program that adds this support (but note that it will only compile with JDK 1.2 or higher):<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; highlight: [5,53,54,55,56,57,58,59]; title: ; quick-code: false; notranslate\" title=\"\">\npackage reflection;\n\nimport java.lang.reflect.Array;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.AccessibleObject;\n\n\n\/**\n*   This class allows the programmer to peek into\n*   a specified class, and also to provide a generic\n*   equals() mechanism.\n*\n*   @author Horstmann &amp; Cornell, CORE Java 1.2, Vol I, p214\n*   @author Bryan J. Higgs, modified &amp; extended 29 Dec 1999\n*\/\npublic class ObjectAnalyzer2\n{\n    private ObjectAnalyzer2()\n    {\n        \/\/ Prevent instantiation\n    }\n    \n    public static String toString(Object obj)\n    {\n        return toString(obj, 0);\n    }\n    \n    private static String toString(Object obj, \n                                   int indentLevel)\n    {\n        String indent = &quot;&quot;;\n        for (int i = 0; i &lt; indentLevel; i++)\n            indent += &quot; &quot;;\n            \n        Class c = obj.getClass();\n        if (c.isArray())\n        {\n            Class type = c.getComponentType();\n            String typeString = type.getName();\n            if (type.isArray())\n                typeString = getArrayType(type);\n                \n            return indent + &quot;Array of &quot; + typeString + &quot;\\n&quot; +\n                   getArrayContents(obj, indentLevel);\n        }\n            \n        String r = indent + c.getName();\n        Class sc = c.getSuperclass();\n        if (sc != null &amp;&amp; !sc.equals(Object.class))\n            r += &quot; extends &quot; + sc;\n        r += &quot;\\n&quot;;\n        Field&#x5B;] fields = c.getDeclaredFields();\n        try\n        {\n            AccessibleObject.setAccessible(fields, true);\n        }\n        catch(SecurityException e)\n        {\n        }\n        for (int i = 0; i &lt; fields.length; i++)\n        {\n            Field field = fields&#x5B;i];\n            r += field.getName() + &quot;=&quot;;\n            String s = &quot;???&quot;;\/\/ Expect access problems\n            try\n            {\n                Object value = field.get(obj);\n                Class vc = value.getClass();\n                if (!vc.isArray())\n                    s = value.toString();\n                else\n                {\n                    s = &quot;\\n&quot;;\n                    s += getArrayContents(value, \n                                          indentLevel + 1);\n                }\n            }\n            catch(NullPointerException e)\n            {\n                s = &quot;null&quot;;\n            }\n            catch(IllegalAccessException e)\n            {}\n            r += s;\n            if (!r.endsWith(&quot;\\n&quot;))\n                r += &quot;\\n&quot;;\n        }\n        return r;\n    }\n    \n    private static String getArrayContents(Object obj, \n                                           int indentLevel)\n    {\n        String indent = &quot;&quot;;\n        for (int i = 0; i &lt; indentLevel; i++)\n            indent += &quot; &quot;;\n            \n        Class c = obj.getClass();\n        String r = &quot;&quot;;\n        int length = Array.getLength(obj);\n        for (int i = 0; i &lt; length; i++)\n        {\n            r += indent + &quot;&#x5B;&quot; + i + &quot;]=&quot;;\n            String s = &quot;???&quot;;\/\/ Expect access problems\n            try\n            {\n                Object value = Array.get(obj, i);\n                Class vc = value.getClass();\n                s = &quot;(&quot; + getArrayType(vc) + &quot;)&quot;;\n                if (!vc.isArray())\n                {\n                    s += value.toString();\n                }\n                else\n                {\n                    s += &quot;\\n&quot; + \n                         getArrayContents(value, \n                                          indentLevel + 1);\n                }\n                \n            }\n            catch(NullPointerException e)\n            {\n                s = &quot;null&quot;;\n            }\n            r += s;\n            if (!r.endsWith(&quot;\\n&quot;))\n                r += &quot;\\n&quot;;\n        }\n        return r;\n    }\n    \n    private static String getArrayType(Class c)\n    {\n        if (!c.isArray())\n            return c.getName();\n        else\n        {\n            \/\/ Use recursion to construct proper string\n            String type = getArrayType(c.getComponentType());\n            return type + &quot;&#x5B;]&quot;;\n        }\n    }\n}\n<\/pre><\/div>\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Instantiating_an_Object\"><\/span>Instantiating an Object<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Using the class&nbsp;<strong>Class<\/strong>, it is possible to dynamically instantiate a class at run time. The following snippet of code shows how this can be done, given just the fully qualified name of the class:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; notranslate\" title=\"\">\nClass c;\n\/\/ Load the class\ntry\n{\n    c = Class.forName(&quot;reflection.Employee&quot;);\n}\ncatch(ClassNotFoundException e)\n{\n    System.err.println(&quot;Class not found&quot;);\n    return;\n}\n        \n\/\/ Instantiate the class\nObject emp;\ntry\n{\n    emp = c.newInstance();\n}\ncatch(InstantiationException e)\n{\n    System.err.println(&quot;Failed to instantiate&quot;);\n}\ncatch(IllegalAccessException e)\n{\n    System.err.println(&quot;Unable to access class&quot;);\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">If the class file cannot be found in the class path, then a <strong>ClassNotFoundException<\/strong> is thrown.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If the specified object cannot be instantiated because it is an interface or is an abstract class, then an&nbsp;<strong>InstantiationException<\/strong>&nbsp;is thrown.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If the specified object cannot be instantiated because the caller does not have access to the object&#8217;s constructor, then an&nbsp;<strong>IllegalAccessException<\/strong>&nbsp;is thrown.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Note that the&nbsp;<strong>newInstance()<\/strong>&nbsp;method attempts to execute the zero-argument constructor for the class.&nbsp;<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">But what if a class doesn&#8217;t have such a constructor? Does this mean that it can&#8217;t be dynamically instantiated?<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">No, it doesn&#8217;t.&nbsp; However, it does mean that you can&#8217;t dynamically instantiate the class using only the class&nbsp;<strong>Class<\/strong>.&nbsp; Instead, you have to use the&nbsp;<strong>Constructor<\/strong>&nbsp;class&#8217;s&nbsp;<strong>newInstance()<\/strong>&nbsp;method:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>public native Object newInstance(Object[] initargs) \n     throws InstantiationException, \n            IllegalAccessException, \n            IllegalArgumentException, \n            InvocationTargetException<\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The&nbsp;<strong>initargs<\/strong>&nbsp;array supplies the values for the parameters to be passed to the constructor. The&nbsp;<strong>newInstance()<\/strong>&nbsp;method attempts to provide the necessary unwrapping conversions from objects (such as&nbsp;<strong>Double<\/strong>,&nbsp;<strong>Integer<\/strong>, etc.) to any expected primitive types (<strong>double<\/strong>,&nbsp;<strong>int<\/strong>, etc.)<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If the number of actual and formal parameters differ, or if an unwrapping conversion fails, or if there is some other parameter mismatch, then an&nbsp;<strong>IllegalArgumentException<\/strong>&nbsp;is thrown.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If the constructor throws an exception, then the exception is wrapped in an&nbsp;<strong>InvocationTargetException<\/strong>, which is then thrown.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s a snippet of code to show how you do it:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; highlight: [13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,40]; title: ; quick-code: false; notranslate\" title=\"\">\nClass c;\n\/\/ Load the class\ntry\n{\n    c = Class.forName(&quot;reflection.Employee&quot;);\n}\ncatch(ClassNotFoundException e)\n{\n    System.err.println(&quot;Class not found&quot;);\n    return;\n}\n\n\/\/ Find a suitable constructor\nClass&#x5B;] paramTypes = new Class&#x5B;] \n{\n    String.class, int.class, double.class, long.class\n};\nConstructor con;\ntry\n{\n    con = c.getConstructor(paramTypes);\n}\ncatch(NoSuchMethodException e)\n{\n    System.err.println(&quot;Can&#039;t find constructor&quot;);\n    return;\n}\n\n\/\/ Construct the parameters for the call\nObject&#x5B;] params = new Object&#x5B;]\n{\n    &quot;Frodus G. Eklogue&quot;, new Integer(45),\n    new Double(34000), new Long(23456)\n};\n\n\/\/ Make the call to instantiate an Employee\nObject emp = null;\ntry\n{\n    emp = con.newInstance(params);\n}\ncatch(InstantiationException e)\n{\n    System.err.println(&quot;Failed to instantiate&quot;);\n}\ncatch(IllegalAccessException e)\n{\n    System.err.println(&quot;Unable to access class&quot;);\n}\ncatch(InvocationTargetException e)\n{\n    System.err.println(&quot;Invocation target threw exception&quot;);\n}\n<\/pre><\/div>\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Creating_an_Array\"><\/span>Creating an Array<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">The&nbsp;<strong>Array<\/strong>&nbsp;class also has two&nbsp;<strong>newInstance()<\/strong>&nbsp;methods that allow you to dynamically create an array of a specified size and type:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>To create a single dimension array<\/li><\/ul>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>public static Object newInstance(Class componentType,\n                                 int length) \n      throws NegativeArraySizeException<\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">which does the equivalent of:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>new componentType[length]<\/strong><\/pre>\n\n\n\n<ul class=\"wp-block-list\"><li>To create a multiple dimension array<\/li><\/ul>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>public static Object newInstance(Class componentType,\n                                 int[] dimensions) \n    throws IllegalArgumentException, \n           NegativeArraySizeException<\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">which does the equivalent of<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>new componentType[dimensions[0]][dimensions[1]]...<\/strong><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Calling_a_Method\"><\/span>Calling a Method<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Just as the&nbsp;<strong>Constructor<\/strong>&nbsp;class provides a&nbsp;<strong>newInstance()<\/strong>&nbsp;method to invoke a chosen constructor for a class, so the&nbsp;<strong>Method<\/strong>&nbsp;class provides an&nbsp;<strong>invoke()<\/strong>&nbsp;method to call a chosen method in the class:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>public native Object invoke(Object obj,\n                            Object[] args) \n    throws IllegalAccessException, \n           IllegalArgumentException, \n           InvocationTargetException<\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s a snippet of an example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\nClass c = emp.getClass(); \/\/ (or similar)\n   ...\n\/\/ Find a suitable method\nClass&#x5B;] methodParams = new Class&#x5B;]\n{\n    String.class, int.class, \n    double.class, long.class\n};\nMethod method;\ntry\n{\n    method = c.getMethod(&quot;init&quot;, methodParams);\n}\ncatch(NoSuchMethodException e)\n{\n    System.err.println(&quot;Can&#039;t find method&quot;);\n    return;\n}\n\n\/\/ Construct parameter list for call\nObject&#x5B;] paramValues = new Object&#x5B;]\n{\n    &quot;Launcelot Hobgoblin&quot;, new Integer(57),\n    new Double(560000.00), new Long(34567)\n};\n\/\/ Do the call...\ntry\n{\n    method.invoke(emp, paramValues);\n}\ncatch(IllegalAccessException e)\n{\n    System.err.println(&quot;Unable to access class&quot;);\n}\ncatch(InvocationTargetException e)\n{\n    System.err.println(&quot;Invocation target threw exception&quot;);\n}\n\n<\/pre><\/div>\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"An_Example\"><\/span>An Example<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s an example of how you can use reflection to dynamically:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Load a class&nbsp;<\/li><li>Create an instance of that class<\/li><li>Invoke a method of that class (a static method and an instance method)<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">First, we have a very simple class that is to be reflected:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage reflectee;\n\nimport java.util.Random;\n\n\/**\n * A class that is to be reflected.\n * When instantiated, it creates a random integer.\n *\/\npublic class ReflectMe\n{\n  \/**\n   * Creates a new instance of ReflectMe.\n   * (This constructor provided for simple instantiation.)\n   *\/\n  public ReflectMe()\n  {\n    this(DEFAULT_MAX_RANDOM_VALUE);\n  }\n  \n  \/**\n   * Creates a new instance of ReflectMe\n   *\n   * @param maxRandomValue -- the random value will be\n   *                          between 0 and this value.\n   *\/\n  public ReflectMe(int maxRandomValue)\n  {\n    m_randomValue = new Random().nextInt(maxRandomValue);\n  }\n  \n  \/**\n   * Gets the random value generated.\n   *\/\n  public int getRandomValue()\n  {\n    return m_randomValue;\n  }\n  \n  \/**\n   * Sets the random value.\n   *\/\n  public void setRandomValue(int value)\n  {\n    System.out.println(&quot;Setting value to &quot; + value);\n    m_randomValue = value;\n  }\n  \n  \/**\n   * Main entry point\n   *\/\n  public static void main(String&#x5B;] args)\n  {\n    if (args.length &lt; 1)\n    {\n      System.err.println(&quot;Usage: ReflectMe &lt;maxRandomValue&gt;&quot;);\n    }\n    else\n    {\n      \/\/ The following will throw a NumberFormatException\n      \/\/ if args&#x5B;0] is not a value integer.\n      int maxRandomValue = Integer.parseInt(args&#x5B;0]);\n      System.out.println(&quot;Generating random integer &lt; &quot; + maxRandomValue);\n      \n      ReflectMe me = new ReflectMe(maxRandomValue);\n      System.out.println(&quot;Random value = &quot; + me.getRandomValue());\n    }\n  }\n  \n  \/\/\/\/ Private data \/\/\/\/\n  private int m_randomValue; \/\/ The generated random integer\n  private static final int DEFAULT_MAX_RANDOM_VALUE = 100;\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Now, here&#8217;s the class that will do the reflection:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage reflector;\n\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Modifier;\n\n\/**\n * Class to use reflection on another class.\n *\/\npublic class MyReflector\n{\n  \/**\n   * Main entry point.\n   *\n   * @param args -- arg&#x5B;0] : the fully qualified class\n   *                         name to reflect\n   *                arg&#x5B;1] : the name of the method to run\n   *                arg&#x5B;2] to arg&#x5B;n] : arguments to pass to the method\n   *\/\n  public static void main(String&#x5B;] args)\n  {\n    if (args.length &lt; 2)\n    {\n      System.err.println(\n          &quot;Usage: MyReflector &lt;fullClassName&gt; &lt;methodToRun&gt; &lt;argToPass&gt;...&quot;);\n    }\n    else\n    {\n      \/\/ Extract the class name and the method\n      String className = args&#x5B;0];\n      String methodName = args&#x5B;1];\n      System.out.println(&quot;Class to reflect: &quot; + className);\n      System.out.println(&quot;Method to call: &quot; + methodName);\n      \/\/ Extract the arguments to pass and construct a new args array\n      String&#x5B;] argsToPass = new String&#x5B;args.length - 2];\n      for (int argIn = 2, argOut = 0; argIn &lt; args.length; argIn++, argOut++)\n      {\n        argsToPass&#x5B;argOut] = args&#x5B;argIn];\n      }\n      System.out.println(&quot;Args to pass: &quot;);\n      for (Object arg : argsToPass)\n      {\n        System.out.println(arg);\n      }\n      \n      \/\/ Do the actual reflection work\n      try\n      {\n        reflectTheClass(className, methodName, argsToPass);\n      }\n      catch (ClassNotFoundException cnfe)\n      {\n        cnfe.printStackTrace();\n      }\n      catch (IllegalArgumentException iae)\n      {\n        iae.printStackTrace();\n      }\n    }\n  }\n  \n  \/**\n   * Does the actual reflection work\n   *\/\n  public static void reflectTheClass(\n      String className, String methodName, String&#x5B;] argsToPass)\n      throws ClassNotFoundException\n  {\n    \/\/ Now, load in the class to be reflected\n    Class theClass = Class.forName(className);\n    \n    System.out.println(&quot;Class loaded; obtaining methods:&quot;);\n    Method&#x5B;] methods = theClass.getMethods();\n    boolean methodFound = false;\n    for (Method method : methods)\n    {\n      String currentMethodName = method.getName();\n      System.out.println(currentMethodName);\n      if (currentMethodName.equals(methodName))\n      {\n        \/\/ We&#039;re making the simplified assumption that we have\n        \/\/ no overloaded methods of this name, so we just choose\n        \/\/ the first one we see.\n        methodFound = true;\n        System.out.println(&quot;Found the specified method&quot;);\n        \/\/ So call it...\n        callTheMethod(theClass, method, argsToPass);\n        \n        \/\/ No need to search through any other methods.\n        return;\n      }\n    }\n    if (!methodFound)\n    {\n      throw new IllegalArgumentException(\n          &quot;Method &#039;&quot; + methodName + &quot;&#039; not found!&quot;);\n    }\n  }\n  \n  \/**\n   * Calls the method from the specified class.\n   * (Makes the simplifying assumption that the method takes\n   *  an array of arguments that matches what we have supplied.)\n   *\/\n  private static void callTheMethod(\n      Class theClass, Method theMethod, String&#x5B;] argsToPass)\n  {\n    int modifiers = theMethod.getModifiers();\n    try\n    {\n      if (Modifier.isStatic(modifiers))\n      {\n        \/\/ The method is static, so we can just call it\n        \/\/ (Note that we&#039;re assuming that this method has\n        \/\/ a signature that matches (String&#x5B;] args) )\n        System.out.println(&quot;Calling static method &#039;&quot; + theMethod.getName() +\n            &quot;&#039; in class &#039;&quot; + theClass.getCanonicalName() + &quot;&#039; ...&quot;);\n        System.out.println(SEPARATOR);\n        \n        \/\/ Note the first parameter (the instance to use) is ignored \n        \/\/ for a static method, so we just supply a null.\n        \/\/ We also assume that the signature for the method is\n        \/\/ (String&#x5B;]) -- for example, a main method.\n        theMethod.invoke(null, new Object&#x5B;] {argsToPass});\n      }\n      else\n      {\n        \/\/ The method is not static (it&#039;s an instance method), \n        \/\/ so we have to first create an instance of the class \n        \/\/ before we can call the method.\n        \n        \/\/ First let&#039;s figure out what we have to supply \n        \/\/ for arguments.\n        System.out.println(&quot;Determining method parameter types.&quot;);\n        Class&#x5B;] parameterTypes = theMethod.getParameterTypes();\n        \n        \/\/ And based on the parameter types, construct an Object array\n        \/\/ to supply the matching values.\n        Object&#x5B;] params = new Object&#x5B;parameterTypes.length];\n        System.out.println(&quot;Total of &quot; + parameterTypes.length + &quot; Parameter types:&quot;);\n        for (int param= 0; param &lt; params.length; param++)\n        {\n          Class paramType = parameterTypes&#x5B;param];\n          System.out.println(&quot;&#x5B;&quot; + param + &quot;] &quot; + paramType);\n          \n          \/\/ Extract the value from the argsToPass array, converting as appropriate:\n          \/\/ Simplification:  Only handle int types\n          \n          \/\/ Is it an int?\n          if (paramType == int.class)\n          {\n            params&#x5B;param] = Integer.parseInt(argsToPass&#x5B;param]); \/\/ autobox\n          }\n          else\n          {\n            \/\/ Do the appropriate conversion for other types\n            \/\/ (left as an exercise for the reader...)\n          }\n        }\n        \n        \/\/ Now, create the instance of the class\n        System.out.println(&quot;Creating instance of class &#039;&quot; +\n            theClass.getCanonicalName() +\n            &quot;&#039; using default (no-arg) constructor...&quot;);\n        Object instance = theClass.newInstance();\n        \n        \/\/ Finally, invoke the method on the instance\n        \/\/ passing in the parameters.\n        System.out.println(&quot;Calling instance method &#039;&quot; + theMethod.getName() +\n            &quot;&#039; in class &#039;&quot; + theClass.getCanonicalName() + &quot;&#039; ...&quot;);\n        System.out.println(SEPARATOR);\n        \n        theMethod.invoke(instance, params);\n      }\n      \n      System.out.println(SEPARATOR);\n      System.out.println(&quot;... Call completed.&quot;);\n    }\n    catch (IllegalArgumentException ex)\n    {\n      ex.printStackTrace();\n    }\n    catch (IllegalAccessException ex)\n    {\n      ex.printStackTrace();\n    }\n    catch (InvocationTargetException ex)\n    {\n      ex.printStackTrace();\n    }\n    catch (InstantiationException ex)\n    {\n      ex.printStackTrace();\n    }\n  }\n  \n  \/\/\/\/ Private data \/\/\/\/\n  private static final String SEPARATOR =\n      &quot;-------------------------------------------------------------------&quot;;\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Note that there is no reference to the &#8216;reflectee&#8217; class from within the &#8216;reflector&#8217; class.&nbsp; The idea is to make it possible for the &#8216;reflector&#8217; class to be able to perform reflection on any class that might be within that JVM&#8217;s class path.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Invoking_a_static_method\"><\/span>Invoking a static method<span class=\"ez-toc-section-end\"><\/span><\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">If we run the <strong>MyReflector<\/strong> class with the following parameters:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>reflectee.ReflectMe main 50<\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">the program outputs the following:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Class to reflect: reflectee.ReflectMe\nMethod to call: main\nArgs to pass: \n50\nClass loaded; obtaining methods:\nmain\nFound the specified method\nCalling static method 'main' in class 'reflectee.ReflectMe' ...\n-------------------------------------------------------------------\nGenerating random integer &lt; 50\nRandom value = 7\n-------------------------------------------------------------------\n... Call completed.<\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In other words, it loaded in the\u00a0<code><strong>reflectee.ReflectMe<\/strong><\/code>\u00a0class, and then invoked that class&#8217;s\u00a0<code><strong>main<\/strong><\/code>\u00a0method, passing in a single argument (50).<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Invoking_an_instance_method\"><\/span>Invoking an instance method<span class=\"ez-toc-section-end\"><\/span><\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Here, we run the MyReflector class with the following parameters:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>reflectee.ReflectMe setRandomValue 42<\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">As a result, the program outputs the following:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Class to reflect: reflectee.ReflectMe\nMethod to call: setRandomValue\nArgs to pass: \n42\nClass loaded; obtaining methods:\nmain\ngetRandomValue\nsetRandomValue\nFound the specified method\nDetermining method parameter types.\nTotal of 1 Parameter types:\n[0] int\nCreating instance of class 'reflectee.ReflectMe' using default (no-arg) constructor...\nCalling instance method 'setRandomValue' in class 'reflectee.ReflectMe' ...\n-------------------------------------------------------------------\nSetting value to 42\n-------------------------------------------------------------------\n... Call completed.<\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In other words, it loaded in the&nbsp;<code><strong>reflectee.ReflectMe<\/strong><\/code>&nbsp;class, created an instance thereof, and then invoked that class&#8217;s&nbsp;<code><strong>setRandomValue<\/strong><\/code>&nbsp;method, passing in a single argument of type int (42).<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The Java Reflection API allows a program to inspect and discover information about classes and other elements of the program. Reflection is used in Serialization and also in JavaBeans, among other applications. The class&nbsp;java.lang.Class&nbsp;is the starting point for the reflection process. The classes in the package&nbsp;java.lang.reflect&nbsp;provide more information for reflection, and are typically used in [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"parent":19,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"_eb_attr":"","ocean_front_end_style_editor":"no","ocean_post_layout":"left-sidebar","ocean_both_sidebars_style":"","ocean_both_sidebars_content_width":0,"ocean_both_sidebars_sidebars_width":0,"ocean_sidebar":"ocs-course-topics-sidebar","ocean_second_sidebar":"0","ocean_disable_margins":"enable","ocean_add_body_class":"","ocean_shortcode_before_top_bar":"","ocean_shortcode_after_top_bar":"","ocean_shortcode_before_header":"","ocean_shortcode_after_header":"","ocean_has_shortcode":"","ocean_shortcode_after_title":"","ocean_shortcode_before_footer_widgets":"","ocean_shortcode_after_footer_widgets":"","ocean_shortcode_before_footer_bottom":"","ocean_shortcode_after_footer_bottom":"","ocean_display_top_bar":"default","ocean_display_header":"default","ocean_header_style":"","ocean_center_header_left_menu":"0","ocean_custom_header_template":"0","ocean_custom_logo":0,"ocean_custom_retina_logo":0,"ocean_custom_logo_max_width":0,"ocean_custom_logo_tablet_max_width":0,"ocean_custom_logo_mobile_max_width":0,"ocean_custom_logo_max_height":0,"ocean_custom_logo_tablet_max_height":0,"ocean_custom_logo_mobile_max_height":0,"ocean_header_custom_menu":"0","ocean_menu_typo_font_family":"0","ocean_menu_typo_font_subset":"","ocean_menu_typo_font_size":0,"ocean_menu_typo_font_size_tablet":0,"ocean_menu_typo_font_size_mobile":0,"ocean_menu_typo_font_size_unit":"px","ocean_menu_typo_font_weight":"","ocean_menu_typo_font_weight_tablet":"","ocean_menu_typo_font_weight_mobile":"","ocean_menu_typo_transform":"","ocean_menu_typo_transform_tablet":"","ocean_menu_typo_transform_mobile":"","ocean_menu_typo_line_height":0,"ocean_menu_typo_line_height_tablet":0,"ocean_menu_typo_line_height_mobile":0,"ocean_menu_typo_line_height_unit":"","ocean_menu_typo_spacing":0,"ocean_menu_typo_spacing_tablet":0,"ocean_menu_typo_spacing_mobile":0,"ocean_menu_typo_spacing_unit":"","ocean_menu_link_color":"","ocean_menu_link_color_hover":"","ocean_menu_link_color_active":"","ocean_menu_link_background":"","ocean_menu_link_hover_background":"","ocean_menu_link_active_background":"","ocean_menu_social_links_bg":"","ocean_menu_social_hover_links_bg":"","ocean_menu_social_links_color":"","ocean_menu_social_hover_links_color":"","ocean_disable_title":"default","ocean_disable_heading":"default","ocean_post_title":"","ocean_post_subheading":"","ocean_post_title_style":"","ocean_post_title_background_color":"","ocean_post_title_background":0,"ocean_post_title_bg_image_position":"","ocean_post_title_bg_image_attachment":"","ocean_post_title_bg_image_repeat":"","ocean_post_title_bg_image_size":"","ocean_post_title_height":0,"ocean_post_title_bg_overlay":0.5,"ocean_post_title_bg_overlay_color":"","ocean_disable_breadcrumbs":"default","ocean_breadcrumbs_color":"","ocean_breadcrumbs_separator_color":"","ocean_breadcrumbs_links_color":"","ocean_breadcrumbs_links_hover_color":"","ocean_display_footer_widgets":"default","ocean_display_footer_bottom":"default","ocean_custom_footer_template":"0","footnotes":""},"class_list":["post-229","page","type-page","status-publish","hentry","entry"],"_links":{"self":[{"href":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-json\/wp\/v2\/pages\/229","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-json\/wp\/v2\/comments?post=229"}],"version-history":[{"count":13,"href":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-json\/wp\/v2\/pages\/229\/revisions"}],"predecessor-version":[{"id":250,"href":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-json\/wp\/v2\/pages\/229\/revisions\/250"}],"up":[{"embeddable":true,"href":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-json\/wp\/v2\/pages\/19"}],"wp:attachment":[{"href":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-json\/wp\/v2\/media?parent=229"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}