{"id":1241,"date":"2022-02-26T06:37:53","date_gmt":"2022-02-26T06:37:53","guid":{"rendered":"https:\/\/mdr.foobrdigital.com\/?p=1241"},"modified":"2022-02-26T06:37:53","modified_gmt":"2022-02-26T06:37:53","slug":"java-reflection","status":"publish","type":"post","link":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/2022\/02\/26\/java-reflection\/","title":{"rendered":"Java Reflection"},"content":{"rendered":"\n<p>In this tutorial, we will learn reflection, a feature in Java programming that allows us to inspect and modify classes, methods, etc.<\/p>\n\n\n\n<p id=\"introduction\">In Java, reflection allows us to inspect and manipulate classes, interfaces, constructors, methods, and fields at run time.<\/p>\n\n\n\n<p>There is a class in Java named&nbsp;<code>Class<\/code>&nbsp;that keeps all the information about objects and classes at runtime. The object of&nbsp;<var>Class<\/var>&nbsp;can be used to perform reflection.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"class\">Reflection of Java Classes<\/h2>\n\n\n\n<p>In order to reflect a Java class, we first need to create an object of&nbsp;<var>Class<\/var>.<\/p>\n\n\n\n<p>And, using the object we can call various methods to get information about methods, fields, and constructors present in a class.<\/p>\n\n\n\n<p>There exists three ways to create objects of Class:<\/p>\n\n\n\n<p><strong>1. Using forName() method<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Dog {...}\n\n\/\/ create object of Class\n\/\/ to reflect the Dog class\nClass a = Class.forName(\"Dog\");<\/code><\/pre>\n\n\n\n<p>Here, the&nbsp;<code>forName()<\/code>&nbsp;method takes the name of the class to be reflected as its argument.<\/p>\n\n\n\n<p><strong>2. Using getClass() method<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ create an object of Dog class\nDog d1 = new Dog();\n\n\/\/ create an object of Class\n\/\/ to reflect Dog\nClass b = d1.getClass();<\/code><\/pre>\n\n\n\n<p>Here, we are using the object of the&nbsp;<var>Dog<\/var>&nbsp;class to create an object of&nbsp;<var>Class<\/var>.<\/p>\n\n\n\n<p><strong>3. Using .class extension<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ create an object of Class\n\/\/ to reflect the Dog class\nClass c = Dog.class;<\/code><\/pre>\n\n\n\n<p>Now that we know how we can create objects of the&nbsp;<code>Class<\/code>. We can use this object to get information about the corresponding class at runtime.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"example\">Example: Java Class Reflection<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.lang.Class;\nimport java.lang.reflect.*;\n\nclass Animal {\n}\n\n\/\/ put this class in different Dog.java file\npublic class Dog extends Animal {\n  public void display() {\n    System.out.println(\"I am a dog.\");\n  }\n}\n\n\/\/ put this in Main.java file\nclass Main {\n  public static void main(String&#91;] args) {\n    try {\n      \/\/ create an object of Dog\n      Dog d1 = new Dog();\n\n      \/\/ create an object of Class\n      \/\/ using getClass()\n      Class obj = d1.getClass();\n\n      \/\/ get name of the class\n      String name = obj.getName();\n      System.out.println(\"Name: \" + name);\n\n      \/\/ get the access modifier of the class\n      int modifier = obj.getModifiers();\n\n      \/\/ convert the access modifier to string\n      String mod = Modifier.toString(modifier);\n      System.out.println(\"Modifier: \" + mod);\n\n      \/\/ get the superclass of Dog\n      Class superClass = obj.getSuperclass();\n      System.out.println(\"Superclass: \" + superClass.getName());\n    }\n\n    catch (Exception e) {\n      e.printStackTrace();\n    }\n  }\n}<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>Name: Dog\nModifier: public\nSuperclass: Animal<\/samp><\/code><\/pre>\n\n\n\n<p>In the above example, we have created a superclass:&nbsp;<var>Animal<\/var>&nbsp;and a subclass:&nbsp;<var>Dog<\/var>. Here, we are trying to inspect the class&nbsp;<var>Dog<\/var>.<\/p>\n\n\n\n<p>Notice the statement,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Class obj = d1.getClass();<\/code><\/pre>\n\n\n\n<p>Here, we are creating an object&nbsp;<var>obj<\/var>&nbsp;of&nbsp;<var>Class<\/var>&nbsp;using the&nbsp;<code>getClass()<\/code>&nbsp;method. Using the object, we are calling different methods of&nbsp;<var>Class<\/var>.<\/p>\n\n\n\n<ul><li><strong>obj.getName()<\/strong>&nbsp;&#8211; returns the name of the class<\/li><li><strong>obj.getModifiers()<\/strong>&nbsp;&#8211; returns the access modifier of the class<\/li><li><strong>obj.getSuperclass()<\/strong>&nbsp;&#8211; returns the super class of the class<\/li><\/ul>\n\n\n\n<p><\/p>\n\n\n\n<p><strong>Note<\/strong>: We are using the&nbsp;<code>Modifier<\/code>&nbsp;class to convert the integer access modifier to a string.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Reflecting Fields, Methods, and Constructors<\/h2>\n\n\n\n<p>The package&nbsp;<code>java.lang.reflect<\/code>&nbsp;provides classes that can be used for manipulating class members. For example,<\/p>\n\n\n\n<ul><li><strong>Method class<\/strong>&nbsp;&#8211; provides information about methods in a class<\/li><li><strong>Field class<\/strong>&nbsp;&#8211; provides information about fields in a class<\/li><li><strong>Constructor class<\/strong>&nbsp;&#8211; provides information about constructors in a class<\/li><\/ul>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"methods\">1. Reflection of Java Methods<\/h2>\n\n\n\n<p>The&nbsp;<code>Method<\/code>&nbsp;class provides various methods that can be used to get information about the methods present in a class. For example,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.lang.Class;\nimport java.lang.reflect.*;\n\nclass Dog {\n\n  \/\/ methods of the class\n  public void display() {\n    System.out.println(\"I am a dog.\");\n  }\n\n  private void makeSound() {\n    System.out.println(\"Bark Bark\");\n  }\n}\n\nclass Main {\n  public static void main(String&#91;] args) {\n    try {\n\n      \/\/ create an object of Dog\n      Dog d1 = new Dog();\n\n      \/\/ create an object of Class\n      \/\/ using getClass()\n      Class obj = d1.getClass();\n\n      \/\/ using object of Class to\n      \/\/ get all the declared methods of Dog\n      Method&#91;] methods = obj.getDeclaredMethods();\n\n      \/\/ create an object of the Method class\n      for (Method m : methods) {\n\n        \/\/ get names of methods\n        System.out.println(\"Method Name: \" + m.getName());\n\n        \/\/ get the access modifier of methods\n        int modifier = m.getModifiers();\n        System.out.println(\"Modifier: \" + Modifier.toString(modifier));\n\n        \/\/ get the return types of method\n        System.out.println(\"Return Types: \" + m.getReturnType());\n        System.out.println(\" \");\n      }\n    }\n    catch (Exception e) {\n      e.printStackTrace();\n    }\n  }\n}<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>Method Name: display\nModifier: public\nReturn Types: void\n \nMethod Name: makeSound\nModifier: private\nReturn Types: void<\/samp><\/code><\/pre>\n\n\n\n<p>In the above example, we are trying to get information about the methods present in the&nbsp;<var>Dog<\/var>&nbsp;class. As mentioned earlier, we have first created an object&nbsp;<var>obj<\/var>&nbsp;of&nbsp;<code>Class<\/code>&nbsp;using the&nbsp;<code>getClass()<\/code>&nbsp;method.<\/p>\n\n\n\n<p>Notice the expression,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Method&#91;] methods = obj.getDeclaredMethod();<\/code><\/pre>\n\n\n\n<p>Here, the&nbsp;<code>getDeclaredMethod()<\/code>&nbsp;returns all the methods present inside the class.<\/p>\n\n\n\n<p>Also, we have created an object&nbsp;<var>m<\/var>&nbsp;of the&nbsp;<code>Method<\/code>&nbsp;class. Here,<\/p>\n\n\n\n<ul><li><strong>m.getName()<\/strong>&nbsp;&#8211; returns the name of a method<\/li><li><strong>m.getModifiers()<\/strong>&nbsp;&#8211; returns the access modifier of methods in integer form<\/li><li><strong>m.getReturnType()<\/strong>&nbsp;&#8211; returns the return type of methods<\/li><\/ul>\n\n\n\n<p>The\u00a0<code>Method<\/code>\u00a0class also provides various other methods that can be used to inspect methods at run time.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"fields\">2. Reflection of Java Fields<\/h2>\n\n\n\n<p>Like methods, we can also inspect and modify different fields of a class using the methods of the&nbsp;<code>Field<\/code>&nbsp;class. For example,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.lang.Class;\nimport java.lang.reflect.*;\n\nclass Dog {\n  public String type;\n}\n\nclass Main {\n  public static void main(String&#91;] args) {\n    try {\n      \/\/ create an object of Dog\n      Dog d1 = new Dog();\n\n      \/\/ create an object of Class\n      \/\/ using getClass()\n      Class obj = d1.getClass();\n\n      \/\/ access and set the type field\n      Field field1 = obj.getField(\"type\");\n      field1.set(d1, \"labrador\");\n\n      \/\/ get the value of the field type\n      String typeValue = (String) field1.get(d1);\n      System.out.println(\"Value: \" + typeValue);\n\n      \/\/ get the access modifier of the field type\n      int mod = field1.getModifiers();\n\n      \/\/ convert the modifier to String form\n      String modifier1 = Modifier.toString(mod);\n      System.out.println(\"Modifier: \" + modifier1);\n      System.out.println(\" \");\n    }\n    \n    catch (Exception e) {\n      e.printStackTrace();\n    }\n  }\n}<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>Value: labrador\nModifier: public<\/samp><\/code><\/pre>\n\n\n\n<p>In the above example, we have created a class named&nbsp;<var>Dog<\/var>. It includes a public field named&nbsp;<var>type<\/var>. Notice the statement,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Field field1 = obj.getField(\"type\");<\/code><\/pre>\n\n\n\n<p>Here, we are accessing the public field of the&nbsp;<var>Dog<\/var>&nbsp;class and assigning it to the object&nbsp;<var>field1<\/var>&nbsp;of the&nbsp;<var>Field<\/var>&nbsp;class.<\/p>\n\n\n\n<p>We then used various methods of the&nbsp;<code>Field<\/code>&nbsp;class:<\/p>\n\n\n\n<ul><li><strong>field1.set()<\/strong>&nbsp;&#8211; sets the value of the field<\/li><li><strong>field1.get()<\/strong>&nbsp;&#8211; returns the value of field<\/li><li><strong>field1.getModifiers()<\/strong>&nbsp;&#8211; returns the value of the field in integer form<\/li><\/ul>\n\n\n\n<p>Similarly, we can also access and modify private fields as well. However, the reflection of private field is little bit different than the public field. For example,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.lang.Class;\nimport java.lang.reflect.*;\n\nclass Dog {\n  private String color;\n}\n\nclass Main {\n  public static void main(String&#91;] args) {\n    try {\n      \/\/ create an object of Dog\n      Dog d1 = new Dog();\n\n      \/\/ create an object of Class\n      \/\/ using getClass()\n      Class obj = d1.getClass();\n\n      \/\/ access the private field color\n      Field field1 = obj.getDeclaredField(\"color\");\n\n      \/\/ allow modification of the private field\n      field1.setAccessible(true);\n\n      \/\/ set the value of color\n      field1.set(d1, \"brown\");\n\n      \/\/ get the value of field color\n      String colorValue = (String) field1.get(d1);\n      System.out.println(\"Value: \" + colorValue);\n\n      \/\/ get the access modifier of color\n      int mod2 = field1.getModifiers();\n\n      \/\/ convert the access modifier to string\n      String modifier2 = Modifier.toString(mod2);\n      System.out.println(\"Modifier: \" + modifier2);\n    }\n    \n    catch (Exception e) {\n      e.printStackTrace();\n    }\n  }\n}<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>Value: brown\nModifier: private<\/samp><\/code><\/pre>\n\n\n\n<p>In the above example, we have created a class named&nbsp;<var>Dog<\/var>. The class contains a private field named&nbsp;<var>color<\/var>. Notice the statement.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Field field1 = obj.getDeclaredField(\"color\");\n\nfield1.setAccessible(true);<\/code><\/pre>\n\n\n\n<p>Here, we are accessing&nbsp;<var>color<\/var>&nbsp;and assigning it to the object&nbsp;<var>field1<\/var>&nbsp;of the&nbsp;<code>Field<\/code>&nbsp;class. We then used&nbsp;<var>field1<\/var>&nbsp;to modify the accessibility of&nbsp;<var>color<\/var>&nbsp;and allows us to make changes to it.<\/p>\n\n\n\n<p>We then used field1 to perform various operations on the private field color.<\/p>\n\n\n\n<p><\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"constructor\">3. Reflection of Java Constructor<\/h2>\n\n\n\n<p>We can also inspect different constructors of a class using various methods provided by the&nbsp;<code>Constructor<\/code>&nbsp;class. For example,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.lang.Class;\nimport java.lang.reflect.*;\n\nclass Dog {\n\n  \/\/ public constructor without parameter\n  public Dog() {\n\n  }\n\n  \/\/ private constructor with a single parameter\n  private Dog(int age) {\n\n  }\n\n}\n\nclass Main {\n  public static void main(String&#91;] args) {\n    try {\n      \/\/ create an object of Dog\n      Dog d1 = new Dog();\n\n      \/\/ create an object of Class\n      \/\/ using getClass()\n      Class obj = d1.getClass();\n\n      \/\/ get all constructors of Dog\n      Constructor&#91;] constructors = obj.getDeclaredConstructors();\n\n      for (Constructor c : constructors) {\n\n        \/\/ get the name of constructors\n        System.out.println(\"Constructor Name: \" + c.getName());\n\n        \/\/ get the access modifier of constructors\n        \/\/ convert it into string form\n        int modifier = c.getModifiers();\n        String mod = Modifier.toString(modifier);\n        System.out.println(\"Modifier: \" + mod);\n\n        \/\/ get the number of parameters in constructors\n        System.out.println(\"Parameters: \" + c.getParameterCount());\n        System.out.println(\"\");\n      }\n    }\n    \n    catch (Exception e) {\n      e.printStackTrace();\n    }\n  }\n}<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>Constructor Name: Dog\nModifier: public     \nParameters: 0        \n\nConstructor Name: Dog\nModifier: private    \nParameters: 1<\/samp><\/code><\/pre>\n\n\n\n<p>In the above example, we have created a class named&nbsp;<var>Dog<\/var>. The class includes two constructors.<\/p>\n\n\n\n<p>We are using reflection to find the information about the constructors of the class. Notice the statement,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Constructor&#91;] constructors = obj.getDeclaredConstructor();<\/code><\/pre>\n\n\n\n<p>Here, the we are accessing all the constructors present in&nbsp;<var>Dog<\/var>&nbsp;and assigning them to an array&nbsp;<var>constructors<\/var>&nbsp;of the&nbsp;<code>Constructor<\/code>&nbsp;type.<\/p>\n\n\n\n<p>We then used object&nbsp;<var>c<\/var>&nbsp;to get different informations about the constructor.<\/p>\n\n\n\n<ul><li><strong>c.getName()<\/strong>&nbsp;&#8211; returns the name of the constructor<\/li><li><strong>c.getModifiers()<\/strong>&nbsp;&#8211; returns the access modifiers of the constructor in integer form<\/li><li><strong>c.getParameterCount()<\/strong>&nbsp;&#8211; returns the number of parameters present in each constructor<\/li><\/ul>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, we will learn reflection, a feature in Java programming that allows us to inspect and modify classes, methods, etc. In Java, reflection allows us to inspect and manipulate classes, interfaces, constructors, methods, and fields at run time. There is a class in Java named&nbsp;Class&nbsp;that keeps all the information about objects and classes [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[556],"tags":[],"_links":{"self":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts\/1241"}],"collection":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/comments?post=1241"}],"version-history":[{"count":0,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts\/1241\/revisions"}],"wp:attachment":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/media?parent=1241"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/categories?post=1241"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/tags?post=1241"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}