{"id":3348,"date":"2017-09-23T12:42:34","date_gmt":"2017-09-23T07:12:34","guid":{"rendered":"http:\/\/www.java2blog.com\/?p=3348"},"modified":"2021-01-12T17:24:34","modified_gmt":"2021-01-12T11:54:34","slug":"java-reflection-tutorial","status":"publish","type":"post","link":"https:\/\/java2blog.com\/java-reflection-tutorial\/","title":{"rendered":"Java Reflection tutorial"},"content":{"rendered":"<h2><span id=\"Introduction\"><span style=\"color: #993366;\">Introduction<\/span><\/span><\/h2>\n<p>Reflection, as we know from the common term, is an image of yourself or something else you see in a mirror or a mirrored surface. Java, being an object-oriented language draws heavily from real-life examples and so is the Reflection API of Java inspired from real life.<br \/>\n<div id=\"toc_container\" class=\"toc_light_blue no_bullets\"><p class=\"toc_title\">Table of Contents<\/p><ul class=\"toc_list\"><li><a href=\"#Introduction\">Introduction<\/a><\/li><li><a href=\"#The_8216reflect8217_package\">The &#8216;reflect&#8217; package<\/a><ul><li><a href=\"#Field\">Field<\/a><\/li><li><a href=\"#Modifier\">Modifier<\/a><\/li><li><a href=\"#Proxy\">Proxy<\/a><\/li><li><a href=\"#Method\">Method<\/a><\/li><li><a href=\"#Constructor\">Constructor<\/a><\/li><li><a href=\"#Array\">Array<\/a><\/li><\/ul><\/li><li><a href=\"#Uses_of_Reflection_in_Java\">Uses of Reflection in Java<\/a><ul><li><a href=\"#Extensibility\">Extensibility<\/a><\/li><li><a href=\"#Developing_IDEs_and_Class_Browsers\">Developing IDEs and Class Browsers<\/a><\/li><li><a href=\"#Debugging_and_Testing_tools\">Debugging and Testing tools<\/a><\/li><\/ul><\/li><li><a href=\"#Disadvantages_of_Reflection\">Disadvantages of Reflection<\/a><ul><li><a href=\"#Low_Performace\">Low Performace<\/a><\/li><li><a href=\"#Security_Risk\">Security Risk<\/a><\/li><li><a href=\"#Exposure_of_Internal_Fields_and_Attributes\">Exposure of Internal Fields and Attributes<\/a><\/li><\/ul><\/li><li><a href=\"#JavalangClass_the_gateway_to_Reflection\">Java.lang.Class \u2013 the gateway to Reflection<\/a><ul><li><a href=\"#Important_Methods_of_javalangClass\">Important Methods of java.lang.Class<\/a><ul><li><a href=\"#forName_method\">forName() method:<\/a><\/li><li><a href=\"#getConstructors_and_getDeclaredConstructors_methods\">getConstructors() and getDeclaredConstructors() methods:<\/a><\/li><li><a href=\"#getMethods_and_getDeclaredMethods\">getMethods() and getDeclaredMethods()<\/a><\/li><li><a href=\"#getFields_and_getDeclaredFields_methods\">getFields() and getDeclaredFields() methods:<\/a><\/li><\/ul><\/li><\/ul><\/li><li><a href=\"#Conclusion\">Conclusion<\/a><\/li><\/ul><\/div>\n\n<p>In Java, the process of analyzing, viewing and modifying all the internal attributes, behaviors and capabilities of a class at runtime is called Reflection. Using the concept of Reflection, a programmer can now manipulate all attributes of a class \u2013 including its methods, constructors, and fields even at runtime, and even invoke methods of that class and get a complete snapshot of it.<\/p>\n<p>Reflection is heavily used in Java frameworks such as <a href=\"https:\/\/www.java2blog.com\/introduction-to-spring-framework\/\">Spring<\/a>, <a href=\"https:\/\/www.java2blog.com\/introduction-to-hibernate-framework\/\">Hibernate<\/a>, Junit etc.<\/p>\n<h2><span id=\"The_8216reflect8217_package\"><span style=\"color: #993366;\"><strong>The &#8216;reflect&#8217; package<\/strong><\/span><\/span><\/h2>\n<p>The core collection of classes and information related to Reflection in Java is encapsulated as the java.lang.reflect package. It contains several interfaces and classes which define methods that are used for reflection of other classes.<\/p>\n<p>Let us have a look at some of the classes within the java.lang.reflect package<\/p>\n<h3><span id=\"Field\"><strong>Field<\/strong><\/span><\/h3>\n<p>This class provides information about the fields present in the class whose reflection is being looked at.<\/p>\n<h3><span id=\"Modifier\"><strong>Modifier<\/strong><\/span><\/h3>\n<p>This class provides information about the class and other members&#8217; access modifiers of the class being reflected.<\/p>\n<h3><span id=\"Proxy\"><strong>Proxy<\/strong><\/span><\/h3>\n<p>This class supports the dynamic proxy classes<\/p>\n<h3><span id=\"Method\"><strong>Method<\/strong><\/span><\/h3>\n<p>This class provides information about the methods of the class being reflected and inspected.<\/p>\n<h3><span id=\"Constructor\"><strong>Constructor<\/strong><\/span><\/h3>\n<p>This class provides information regarding the constructors of the class being reflected and inspected.<\/p>\n<h3><span id=\"Array\"><strong>Array<\/strong><\/span><\/h3>\n<p>This class allows the programmer to dynamically create and manipulate Arrays<\/p>\n<p>Other than these, the java.lang.Class class is one of the most important classes in use for Reflection as the objects of Class can store the actual information of the class that we want to investigate or reflect.<\/p>\n<h2><span id=\"Uses_of_Reflection_in_Java\"><span style=\"color: #993366;\"><strong>Uses of Reflection in Java<\/strong><\/span><\/span><\/h2>\n<h3><span id=\"Extensibility\"><strong>Extensibility<\/strong><\/span><\/h3>\n<p>Using the concepts of reflection, a programmer can make use of externally available user-defined classes by creating instances of those extensible objects by using their fully qualified name<\/p>\n<h3><span id=\"Developing_IDEs_and_Class_Browsers\"><strong>Developing IDEs and Class Browsers<\/strong><\/span><\/h3>\n<p>IDEs, especially those which are capable of visual development, such as Eclipse or Netbeans, and class browsers can make extensive use of Reflection. Using these, the visual development environments make the information of the classes readily available to the user so that they can write proper code.<\/p>\n<h3><span id=\"Debugging_and_Testing_tools\"><strong>Debugging and Testing tools<\/strong><\/span><\/h3>\n<p>Debugging requires the ability to view internal details of a class which include its private members.Debugging and Testing tools may use reflection to make systematic invocations to the classes by use of reflection and ensure test case coverage.<\/p>\n<h2><span id=\"Disadvantages_of_Reflection\"><span style=\"color: #f89820;\"><strong>Disadvantages of Reflection<\/strong><\/span><\/span><\/h2>\n<p>Inspite of being an extremely powerful tool, Reflection API and its usage does have a set of disadvantages such as,<\/p>\n<h3><span id=\"Low_Performace\"><strong>Low Performace<\/strong><\/span><\/h3>\n<p>The use of reflection API can lead to high performance overhead and lead to lower performance. This is because many functionalities make use of dynamic resolution which prevents to the use of certain Virtual machine optimisations. As it tends to slow down processing, it isn&#8217;t recommended for use in sections of code that require high availability and low turnaround.<\/p>\n<h3><span id=\"Security_Risk\"><strong>Security Risk<\/strong><\/span><\/h3>\n<p>Reflection API requires cetain security permissions that are not available during execution under a securely managed system. Also, the security permission requirements can pose a threat to code residing in a secure system.<\/p>\n<h3><span id=\"Exposure_of_Internal_Fields_and_Attributes\"><strong>Exposure of Internal Fields and Attributes<\/strong><\/span><\/h3>\n<p>Due to the ability of Reflection API to access private members and invoke private functions, the internal details of classes and entities are exposed to the outside world and defeats the purpose of Abstraction in object oriented concepts, which may be seen as a violation of object oriented programming concepts.<\/p>\n<p>Now that we have had an overview of the basic idea of Reflection, let us go through the java.lang.Class class which plays the most significant role in reflection in java.<\/p>\n<h2><span id=\"JavalangClass_the_gateway_to_Reflection\"><span style=\"color: #993366;\"><strong>Java.lang.Class \u2013 the gateway to Reflection<\/strong><\/span><\/span><\/h2>\n<p>The Class is a final class in the java.lang package of Java&#8217;s standard library, and extends the Object class which forms the basis of all classes in java. An instance of the class Class is used to represent both classes and interfaces in a Java application which is running. Using an instance of Class, we can view, analyse and modify the attributes of a class while it is running, and can even invoke methods of that class.<\/p>\n<h3><span id=\"Important_Methods_of_javalangClass\"><strong>Important Methods of java.lang.Class<\/strong><\/span><\/h3>\n<p>The Class class has a wide variety of methods that are useful in obtaining a reflection of the class executing and performing a wide range of actions with that class. Some of these methods are:<\/p>\n<h4><span id=\"forName_method\"><strong>forName() method:<\/strong><\/span><\/h4>\n<p>This method accepts the full qualified name of a class or an interface as an argument and returns an instance of the class associated with the qualifed name, including all its attributes and behaviours.<\/p>\n<p>The syntax for the forName method is as follows:<\/p>\n<pre class=\"java\" name=\"code\">static Class&lt;?&gt; forName(String className)\n<\/pre>\n<p>Let us see an example of the forName method:<\/p>\n<pre class=\"java\" name=\"code\">class TestClass{}\nclass ReflectionTest\n{\n public static void main(String args[])\n {\n  Class c = null;\ntry {\n    c = Class.forName(\"TestClass\");\n} catch (ClassNotFoundException e) {\n    System.out.println(e.getMessage());\n}\n  System.out.println(c.getName());\n }\n}\n\n<\/pre>\n<p>The above code generates the following output:<\/p>\n<div class=\"content-box-green\">TestClass<\/div>\n<h4><span id=\"getConstructors_and_getDeclaredConstructors_methods\"><strong>getConstructors() and getDeclaredConstructors() methods:<\/strong><\/span><\/h4>\n<p>The getConstructors() method returns an array of the declared public constructors of the invoking object in the form of java.lang.reflect.Constructor objects. The getDeclaredConstructors() method returns all the constructors of the invoking object including non-public members.<\/p>\n<p>The syntax for both getConstructors() and getDeclaredConstructors() are as follows:<\/p>\n<pre class=\"java\" name=\"code\">Constructor&lt; ?&gt;[] getConstructors();\nConstructor&lt; ?&gt;[] getDeclaredConstructors();\n<\/pre>\n<p>Let us see an example of the use of the above methods:<\/p>\n<pre class=\"java\" name=\"code\">package org.arpit.java2blog;\n\nimport java.lang.reflect.Constructor;\n\nclass TestClass{\n    public TestClass(){}\n    protected TestClass(Integer a){}\n}\n\npublic class ReflectionTest\n{\n    public static void main(String args[])\n    {\n        try\n        {\n            Class c = Class.forName(\"org.arpit.java2blog.TestClass\");\n            System.out.println(\"Using getConstructors()\");\n            Constructor&lt; TestClass&gt;[] ct = c.getConstructors();\n            for(int i=0; i&lt; ct.length; i++)\n            { System.out.println(ct[i]); }\n            System.out.println(\"====================\");\n            System.out.println(\"Using getDeclaredConstructors()\");\n            Constructor&lt; TestClass&gt;[] cdt = c.getDeclaredConstructors();\n            for(int i=0;i&lt; cdt.length;i++)\n            { System.out.println(cdt[i]);}\n\n        }\n        catch(Exception e)\n        { e.printStackTrace();}\n    }\n}\n<\/pre>\n<p>The above code on execution produces the following output:<\/p>\n<div class=\"content-box-green\">\nUsing getConstructors()<br \/>\npublic org.arpit.java2blog.TestClass()<br \/>\n====================<br \/>\nUsing getDeclaredConstructors()<br \/>\npublic org.arpit.java2blog.TestClass()<br \/>\nprotected org.arpit.java2blog.TestClass(java.lang.Integer)\n<\/div>\n<h4><span id=\"getMethods_and_getDeclaredMethods\"><strong>getMethods() and getDeclaredMethods()<\/strong><\/span><\/h4>\n<p>The getMethods() function of java.lang.Class returns an array of java.lang.reflect.Method instances that reflect and return all the public methods of the invoking object. On the other hand, the getDeclaredMethods() function returns only the methods declared by the programmer.<\/p>\n<p>The syntax for both functions are as follows:<\/p>\n<pre class=\"java\" name=\"code\">Method&lt; ?&gt;[] getMethods();\nMethod&lt; ?&gt;[] getDeclaredMethods();\n<\/pre>\n<p>Let us see an example of the use of the above methods:<\/p>\n<pre class=\"java\" name=\"code\">package org.arpit.java2blog;\n\nimport java.lang.reflect.Method;\n\nclass TestClass {\n    public void put() {\n    }\n\n    protected int show() {\n        return 1;\n    }\n\n}\n\npublic class ReflectionTest {\n    public static void main(String args[]) {\n\n        try {\n            Class c = Class.forName(\"org.arpit.java2blog.TestClass\");\n            Method mr[] = c.getMethods();\n            System.out.println(\"==================\");\n            System.out.println(\"Using getMethods()\");\n            System.out.println(\"==================\");\n            for (int i = 0; i < mr.length; i++) {\n                System.out.println(mr[i]);\n            }\n            Method md[] = c.getDeclaredMethods();\n            System.out.println(\"===========================\");\n            System.out.println(\"Using getDeclaredMethods()\");\n            System.out.println(\"============================\");\n            for (int i = 0; i < md.length; i++) {\n                System.out.println(md[i]);\n            }\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n}\n<\/pre>\n<p>The above code on execution produces the following result:<\/p>\n<div class=\"content-box-green\">==================<br \/>\nUsing getMethods()<br \/>\n==================<br \/>\npublic void org.arpit.java2blog.TestClass2.put()<br \/>\npublic final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException<br \/>\npublic final native void java.lang.Object.wait(long) throws java.lang.InterruptedException<br \/>\npublic final void java.lang.Object.wait() throws java.lang.InterruptedException<br \/>\npublic boolean java.lang.Object.equals(java.lang.Object)<br \/>\npublic java.lang.String java.lang.Object.toString()<br \/>\npublic native int java.lang.Object.hashCode()<br \/>\npublic final native java.lang.Class java.lang.Object.getClass()<br \/>\npublic final native void java.lang.Object.notify()<br \/>\npublic final native void java.lang.Object.notifyAll()<br \/>\n===========================<br \/>\nUsing getDeclaredMethods()<br \/>\n============================<br \/>\npublic void org.arpit.java2blog.TestClass2.put()<br \/>\nprotected int org.arpit.java2blog.TestClass2.show()\n<\/div>\n<p>Thus you can see that the getMethods() method returns all the public methods of the object including superclasses, whereas getDeclaredMethods() only returned user-declared methods.<\/p>\n<h4><span id=\"getFields_and_getDeclaredFields_methods\"><strong>getFields() and getDeclaredFields() methods:<\/strong><\/span><\/h4>\n<p>The getFields() methods returns an array consisting of java.lang.Field objects which display all the public attributes of the invoking class or interface. On the other hand, the getDeclaredFields() method returns an array of Field objects which represent all the fields declkared in the invoking class or interface.<\/p>\n<p>The syntax of the methods are as follows:<\/p>\n<pre class=\"java\" name=\"code\">Field&lt; ?&gt;[] getFields();\nField&lt; ?&gt;[] getDeclaredFields();\n<\/pre>\n<p>Let us see an example of the above methods:<\/p>\n<pre class=\"java\" name=\"code\">package org.arpit.java2blog;\n\nimport java.lang.reflect.Field;\n\nclass TestClass {\n    public int a;\n    String b;\n}\n\npublic class ReflectionTest {\n    public static void main(String args[]) {\n        try {\n            Class c = Class.forName(\"org.arpit.java2blog.TestClass\");\n            Field ff[] = c.getFields();\n\n            System.out.println(\"Using getFields() method\");\n            System.out.println(\"=======================\");\n            for (int i = 0; i < ff.length; i++) {\n                System.out.println(ff[i]);\n            }\n            Field f[] = c.getDeclaredFields();\n            System.out.println(\"=======================\");\n            System.out.println(\"Using getDeclaredFields() method\");\n            System.out.println(\"=======================\");\n            for (int i = 0; i < f.length; i++) {\n                System.out.println(f[i]);\n            }\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n}\n<\/pre>\n<p>The above code produces the following result on execution.<\/p>\n<div class=\"content-box-green\">\nUsing getFields() method<br \/>\n=======================<br \/>\npublic int org.arpit.java2blog.TestClass.a<br \/>\n=======================<br \/>\nUsing getDeclaredFields() method<br \/>\n=======================<br \/>\npublic int org.arpit.java2blog.TestClass.a<br \/>\njava.lang.String org.arpit.java2blog.TestClass.b\n<\/div>\n<h2><span id=\"Conclusion\"><span style=\"color: #993366;\">Conclusion<\/span><\/span><\/h2>\n<p>Java's greatest positives is that the design of Java was made such as to encapsulate a diversely dynamic environment \u2013 Classes are loaded dynamically, methods are bound dynamically, variables are created dynamically. This led to the idea of manipulating the classes and viewing them dynamically which materialized as the Reflection API of Java. Reflection helps to make Java a dynamic language that further enhances the benefits of the language.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Table of ContentsIntroductionThe &#8216;reflect&#8217; packageFieldModifierProxyMethodConstructorArrayUses of Reflection in JavaExtensibilityDeveloping IDEs and Class BrowsersDebugging and Testing toolsDisadvantages of ReflectionLow PerformaceSecurity RiskExposure of Internal Fields and AttributesJava.lang.Class \u2013 the gateway to ReflectionImportant Methods of java.lang.ClassforName() method:getConstructors() and getDeclaredConstructors() methods:getMethods() and getDeclaredMethods()getFields() and getDeclaredFields() methods:Conclusion Introduction Reflection, as we know from the common term, is an image of [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"_mi_skip_tracking":false},"categories":[141],"tags":[],"_links":{"self":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/3348"}],"collection":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/comments?post=3348"}],"version-history":[{"count":0,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/3348\/revisions"}],"wp:attachment":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/media?parent=3348"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/categories?post=3348"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/tags?post=3348"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}