<p>What is reflection, and why is it useful?</p>
<p>I'm particularly interested in Java, but I assume the principles are the same in any language.</p>

[{'answer_id': 37632, 'author': 'Matt Sheppard', 'author_id': 797, 'author_profile': 'https://Stackoverflow.com/users/797', 'pm_score': 12, 'selected': True, 'text': '<p>The name reflection is used to describe code which is able to inspect other code in the same system (or itself).</p>\n\n<p>For example, say you have an object of an unknown type in Java, and you would like to call a \'doSomething\' method on it if one exists. Java\'s static typing system isn\'t really designed to support this unless the object conforms to a known interface, but using reflection, your code can look at the object and find out if it has a method called \'doSomething\' and then call it if you want to.</p>\n\n<p>So, to give you a code example of this in Java (imagine the object in question is foo) :</p>\n\n<pre><code>Method method = foo.getClass().getMethod("doSomething", null);\nmethod.invoke(foo, null);\n</code></pre>\n\n<p>One very common use case in Java is the usage with annotations. JUnit 4, for example, will use reflection to look through your classes for methods tagged with the @Test annotation, and will then call them when running the unit test.</p>\n\n<p>There are some good reflection examples to get you started at <a href="http://docs.oracle.com/javase/tutorial/reflect/index.html" rel="noreferrer">http://docs.oracle.com/javase/tutorial/reflect/index.html</a></p>\n\n<p>And finally, yes, the concepts are pretty much similar in other statically typed languages which support reflection (like C#). In dynamically typed languages, the use case described above is less necessary (since the compiler will allow any method to be called on any object, failing at runtime if it does not exist), but the second case of looking for methods which are marked or work in a certain way is still common.</p>\n\n<p><strong>Update from a comment:</strong></p>\n\n<blockquote>\n  <p>The ability to inspect the code in the system and see object types is\n  not reflection, but rather Type Introspection. Reflection is then the\n  ability to make modifications at runtime by making use of\n  introspection. The distinction is necessary here as some languages\n  support introspection, but do not support reflection. One such example\n  is C++</p>\n</blockquote>\n'}, {'answer_id': 37634, 'author': 'Jorge Córdoba', 'author_id': 2695, 'author_profile': 'https://Stackoverflow.com/users/2695', 'pm_score': 4, 'selected': False, 'text': "<p>Reflection is a set of functions which allows you to access the runtime information of your program and modify it behavior (with some limitations).</p>\n\n<p>It's useful because it allows you to change the runtime behavior depending on the meta information of your program, that is, you can check the return type of a function and change the way you handle the situation.</p>\n\n<p>In C# for example you can load an assembly (a .dll) in runtime an examine it, navigating through the classes and taking actions according to what you found. It also let you create an instance of a class on runtime, invoke its method, etc.</p>\n\n<p>Where can it be useful? Is not useful every time but for concrete situations. For example you can use it to get the name of the class for logging purposes, to dynamically create handlers for events according to what's specified on a configuration file and so on...</p>\n"}, {'answer_id': 37635, 'author': 'Mendelt', 'author_id': 3320, 'author_profile': 'https://Stackoverflow.com/users/3320', 'pm_score': 6, 'selected': False, 'text': "<p>Not every language supports reflection, but the principles are usually the same in languages that support it.</p>\n<p>Reflection is the ability to &quot;reflect&quot; on the structure of your program. Or more concrete. To look at the objects and classes you have and programmatically get back information on the methods, fields, and interfaces they implement. You can also look at things like annotations.</p>\n<p>It's useful in a lot of situations. Everywhere you want to be able to dynamically plug in classes into your code. Lots of object relational mappers use reflection to be able to instantiate objects from databases without knowing in advance what objects they're going to use. Plug-in architectures is another place where reflection is useful. Being able to dynamically load code and determine if there are types there that implement the right interface to use as a plugin is important in those situations.</p>\n"}, {'answer_id': 37638, 'author': 'Liedman', 'author_id': 890, 'author_profile': 'https://Stackoverflow.com/users/890', 'pm_score': 8, 'selected': False, 'text': '<blockquote>\n  <p><strong>Reflection</strong> is a language\'s ability to inspect and dynamically call classes, methods, attributes, etc. at runtime.</p>\n</blockquote>\n\n<p>For example, all objects in Java have the method <code>getClass()</code>, which lets you determine the object\'s class even if you don\'t know it at compile time (e.g. if you declared it as an <code>Object</code>) - this might seem trivial, but such reflection is not possible in less dynamic languages such as <code>C++</code>. More advanced uses lets you list and call methods, constructors, etc.</p>\n\n<p>Reflection is important since it lets you write programs that do not have to "know" everything at compile time, making them more dynamic, since they can be tied together at runtime. The code can be written against known interfaces, but the actual classes to be used can be instantiated using reflection from configuration files.</p>\n\n<p>Lots of modern frameworks use reflection extensively for this very reason. Most other modern languages use reflection as well, and in scripting languages (such as Python) they are even more tightly integrated, since it feels more natural within the general programming model of those languages.</p>\n'}, {'answer_id': 37659, 'author': 'toolkit', 'author_id': 3295, 'author_profile': 'https://Stackoverflow.com/users/3295', 'pm_score': 6, 'selected': False, 'text': '<p>Reflection is a key mechanism to allow an application or framework to work with code that might not have even been written yet!</p>\n\n<p>Take for example your typical web.xml file. This will contain a list of servlet elements, which contain nested servlet-class elements. The servlet container will process the web.xml file, and create new a new instance of each servlet class through reflection.</p>\n\n<p>Another example would be the Java API for XML Parsing <a href="http://en.wikipedia.org/wiki/Java_API_for_XML_Processing" rel="noreferrer">(JAXP)</a>. Where an XML parser provider is \'plugged-in\' via well-known system properties, which are used to construct new instances through reflection.</p>\n\n<p>And finally, the most comprehensive example is <a href="http://www.springframework.org/" rel="noreferrer">Spring</a> which uses reflection to create its beans, and for its heavy use of proxies</p>\n'}, {'answer_id': 39918, 'author': 'Ben Williams', 'author_id': 2453, 'author_profile': 'https://Stackoverflow.com/users/2453', 'pm_score': 7, 'selected': False, 'text': '<p>One of my favorite uses of reflection is the below Java dump method. It takes any object as a parameter and uses the Java reflection API to print out every field name and value.</p>\n\n<pre><code>import java.lang.reflect.Array;\nimport java.lang.reflect.Field;\n\npublic static String dump(Object o, int callCount) {\n    callCount++;\n    StringBuffer tabs = new StringBuffer();\n    for (int k = 0; k &lt; callCount; k++) {\n        tabs.append("\\t");\n    }\n    StringBuffer buffer = new StringBuffer();\n    Class oClass = o.getClass();\n    if (oClass.isArray()) {\n        buffer.append("\\n");\n        buffer.append(tabs.toString());\n        buffer.append("[");\n        for (int i = 0; i &lt; Array.getLength(o); i++) {\n            if (i &lt; 0)\n                buffer.append(",");\n            Object value = Array.get(o, i);\n            if (value.getClass().isPrimitive() ||\n                    value.getClass() == java.lang.Long.class ||\n                    value.getClass() == java.lang.String.class ||\n                    value.getClass() == java.lang.Integer.class ||\n                    value.getClass() == java.lang.Boolean.class\n                    ) {\n                buffer.append(value);\n            } else {\n                buffer.append(dump(value, callCount));\n            }\n        }\n        buffer.append(tabs.toString());\n        buffer.append("]\\n");\n    } else {\n        buffer.append("\\n");\n        buffer.append(tabs.toString());\n        buffer.append("{\\n");\n        while (oClass != null) {\n            Field[] fields = oClass.getDeclaredFields();\n            for (int i = 0; i &lt; fields.length; i++) {\n                buffer.append(tabs.toString());\n                fields[i].setAccessible(true);\n                buffer.append(fields[i].getName());\n                buffer.append("=");\n                try {\n                    Object value = fields[i].get(o);\n                    if (value != null) {\n                        if (value.getClass().isPrimitive() ||\n                                value.getClass() == java.lang.Long.class ||\n                                value.getClass() == java.lang.String.class ||\n                                value.getClass() == java.lang.Integer.class ||\n                                value.getClass() == java.lang.Boolean.class\n                                ) {\n                            buffer.append(value);\n                        } else {\n                            buffer.append(dump(value, callCount));\n                        }\n                    }\n                } catch (IllegalAccessException e) {\n                    buffer.append(e.getMessage());\n                }\n                buffer.append("\\n");\n            }\n            oClass = oClass.getSuperclass();\n        }\n        buffer.append(tabs.toString());\n        buffer.append("}\\n");\n    }\n    return buffer.toString();\n}\n</code></pre>\n'}, {'answer_id': 9155976, 'author': 'pramod', 'author_id': 1191613, 'author_profile': 'https://Stackoverflow.com/users/1191613', 'pm_score': 4, 'selected': False, 'text': '<p>As per my understanding:</p>\n\n<p>Reflection allows programmer to access entities in program dynamically. i.e. while coding an application if programmer is unaware about a class or its methods, he can make use of such class dynamically (at run time) by using reflection.</p>\n\n<p>It is frequently used in scenarios where a class name changes frequently. If such a situation arises, then it is complicated for the programmer to rewrite the application and change the name of the class again and again.</p>\n\n<p>Instead, by using reflection, there is need to worry about a possibly changing class name.</p>\n'}, {'answer_id': 11159447, 'author': 'human.js', 'author_id': 1198898, 'author_profile': 'https://Stackoverflow.com/users/1198898', 'pm_score': 5, 'selected': False, 'text': '<p><strong>Example:</strong></p>\n\n<p>Take for example a remote application which gives your application an object which you obtain using their API Methods . Now based on the object you might need to perform some sort of computation . </p>\n\n<p>The provider guarantees that object can be of 3 types and we need to perform computation based on what type of object .</p>\n\n<p>So we might implement in 3 classes each containing a different logic .Obviously the object  information is available in runtime so you cannot statically code to perform computation hence reflection is used to instantiate the object of the class that you require to perform the computation based on the object received from the provider .</p>\n'}, {'answer_id': 16406534, 'author': 'Ess Kay', 'author_id': 2267583, 'author_profile': 'https://Stackoverflow.com/users/2267583', 'pm_score': 3, 'selected': False, 'text': '<p><code>Reflection</code> has many <strong>uses</strong>. The one I am more familiar with, is to be able to create code on the fly. </p>\n\n<blockquote>\n  <p>IE: dynamic classes, functions, constructors - based on any data\n  (xml/array/sql results/hardcoded/etc..)</p>\n</blockquote>\n'}, {'answer_id': 17531269, 'author': 'Nikhil Shekhar', 'author_id': 1772534, 'author_profile': 'https://Stackoverflow.com/users/1772534', 'pm_score': 5, 'selected': False, 'text': '<p>Reflection allows instantiation of new objects, invocation of methods, and get/set operations on class variables dynamically at run time without having prior knowledge of its implementation.</p>\n\n<pre><code>Class myObjectClass = MyObject.class;\nMethod[] method = myObjectClass.getMethods();\n\n//Here the method takes a string parameter if there is no param, put null.\nMethod method = aClass.getMethod("method_name", String.class); \n\nObject returnValue = method.invoke(null, "parameter-value1");\n</code></pre>\n\n<p>In above example the null parameter is the object you want to invoke the method on. If the method is static you supply null. If the method is not static, then while invoking you need to supply a valid MyObject instance instead of null.</p>\n\n<p>Reflection also allows you to access private member/methods of a class:</p>\n\n<pre><code>public class A{\n\n  private String str= null;\n\n  public A(String str) {\n  this.str= str;\n  }\n}\n</code></pre>\n\n<p>.</p>\n\n<pre><code>A obj= new A("Some value");\n\nField privateStringField = A.class.getDeclaredField("privateString");\n\n//Turn off access check for this field\nprivateStringField.setAccessible(true);\n\nString fieldValue = (String) privateStringField.get(obj);\nSystem.out.println("fieldValue = " + fieldValue);\n</code></pre>\n\n<ul>\n<li>For inspection of classes (also know as introspection) you don\'t need to import the reflection package (<code>java.lang.reflect</code>). Class metadata can be accessed through <code>java.lang.Class</code>.</li>\n</ul>\n\n<p>Reflection is a very powerful API but it may slow down the application if used in excess, as it resolves all the types at runtime.</p>\n'}, {'answer_id': 25721335, 'author': 'VeKe', 'author_id': 1878022, 'author_profile': 'https://Stackoverflow.com/users/1878022', 'pm_score': 5, 'selected': False, 'text': '<p>Java Reflection is quite powerful and can be very useful.\nJava Reflection makes it possible <strong>to inspect classes, interfaces, fields and methods at runtime,</strong> without knowing the names of the classes, methods etc. at compile time.\nIt is also possible to <strong>instantiate new objects, invoke methods and get/set field values using reflection.</strong></p>\n\n<p><strong>A quick Java Reflection example to show you what using reflection looks like:</strong></p>\n\n<pre><code>Method[] methods = MyObject.class.getMethods();\n\n    for(Method method : methods){\n        System.out.println("method = " + method.getName());\n    }\n</code></pre>\n\n<p>This example obtains the Class object from the class called MyObject. Using the class object the example gets a list of the methods in that class, iterates the methods and print out their names.</p>\n\n<p><a href="http://tutorials.jenkov.com/java-reflection/classes.html" rel="noreferrer">Exactly how all this works is explained here</a></p>\n\n<p><strong>Edit</strong>: After almost 1 year I am editing this answer as while reading about reflection I got few more uses of Reflection.</p>\n\n<ul>\n<li>Spring uses bean configuration such as:</li>\n</ul>\n\n<p><br></p>\n\n<pre><code>&lt;bean id="someID" class="com.example.Foo"&gt;\n    &lt;property name="someField" value="someValue" /&gt;\n&lt;/bean&gt;\n</code></pre>\n\n<p>When the Spring context processes this &lt; bean > element, it will use Class.forName(String) with the argument "com.example.Foo" to instantiate that Class. </p>\n\n<p>It will then again use reflection to get the appropriate setter for the &lt; property > element and set its value to the specified value.</p>\n\n<ul>\n<li>Junit uses Reflection especially for testing Private/Protected methods.</li>\n</ul>\n\n<p>For Private methods,</p>\n\n<pre><code>Method method = targetClass.getDeclaredMethod(methodName, argClasses);\nmethod.setAccessible(true);\nreturn method.invoke(targetObject, argObjects);\n</code></pre>\n\n<p>For private fields,</p>\n\n<pre><code>Field field = targetClass.getDeclaredField(fieldName);\nfield.setAccessible(true);\nfield.set(object, value);\n</code></pre>\n'}, {'answer_id': 25953852, 'author': 'catch23', 'author_id': 1498427, 'author_profile': 'https://Stackoverflow.com/users/1498427', 'pm_score': 4, 'selected': False, 'text': "<p>I just want to add some points to all that was listed.</p>\n<p>With <strong>Reflection API</strong> you can write a universal <code>toString()</code> method for any object.</p>\n<p>It could be useful for debugging.</p>\n<p>Here is some example:</p>\n<pre><code>class ObjectAnalyzer {\n\n   private ArrayList&lt;Object&gt; visited = new ArrayList&lt;Object&gt;();\n\n   /**\n    * Converts an object to a string representation that lists all fields.\n    * @param obj an object\n    * @return a string with the object's class name and all field names and\n    * values\n    */\n   public String toString(Object obj) {\n      if (obj == null) return &quot;null&quot;;\n      if (visited.contains(obj)) return &quot;...&quot;;\n      visited.add(obj);\n      Class cl = obj.getClass();\n      if (cl == String.class) return (String) obj;\n      if (cl.isArray()) {\n         String r = cl.getComponentType() + &quot;[]{&quot;;\n         for (int i = 0; i &lt; Array.getLength(obj); i++) {\n            if (i &gt; 0) r += &quot;,&quot;;\n            Object val = Array.get(obj, i);\n            if (cl.getComponentType().isPrimitive()) r += val;\n            else r += toString(val);\n         }\n         return r + &quot;}&quot;;\n      }\n\n      String r = cl.getName();\n      // inspect the fields of this class and all superclasses\n      do {\n         r += &quot;[&quot;;\n         Field[] fields = cl.getDeclaredFields();\n         AccessibleObject.setAccessible(fields, true);\n         // get the names and values of all fields\n         for (Field f : fields) {\n            if (!Modifier.isStatic(f.getModifiers())) {\n               if (!r.endsWith(&quot;[&quot;)) r += &quot;,&quot;;\n               r += f.getName() + &quot;=&quot;;\n               try {\n                  Class t = f.getType();\n                  Object val = f.get(obj);\n                  if (t.isPrimitive()) r += val;\n                  else r += toString(val);\n               } catch (Exception e) {\n                  e.printStackTrace();\n               }\n            }\n         }\n         r += &quot;]&quot;;\n         cl = cl.getSuperclass();\n      } while (cl != null);\n\n      return r;\n   }    \n}\n</code></pre>\n"}, {'answer_id': 26424561, 'author': 'Desmond Smith', 'author_id': 2115148, 'author_profile': 'https://Stackoverflow.com/users/2115148', 'pm_score': 7, 'selected': False, 'text': '<p><strong>Uses of Reflection</strong></p>\n\n<p>Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. With that caveat in mind, reflection is a powerful technique and can enable applications to perform operations which would otherwise be impossible.</p>\n\n<p><strong>Extensibility Features</strong></p>\n\n<p>An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.\nClass Browsers and Visual Development Environments\nA class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code.\nDebuggers and Test Tools\nDebuggers need to be able to examine private members in classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to ensure a high level of code coverage in a test suite.</p>\n\n<p><strong>Drawbacks of Reflection</strong></p>\n\n<p>Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.</p>\n\n<ul>\n<li><strong>Performance Overhead</strong></li>\n</ul>\n\n<p>Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations cannot be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts and should be avoided in sections of code which are called frequently in performance-sensitive applications.</p>\n\n<ul>\n<li><strong>Security Restrictions</strong></li>\n</ul>\n\n<p>Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important consideration for code which has to run in a restricted security context, such as in an Applet.</p>\n\n<ul>\n<li><strong>Exposure of Internals</strong></li>\n</ul>\n\n<p>Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private fields and methods, the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.</p>\n\n<p>source: <a href="https://docs.oracle.com/javase/tutorial/reflect/" rel="noreferrer">The Reflection API</a></p>\n'}, {'answer_id': 26771874, 'author': 'Isuru Jayakantha', 'author_id': 4216954, 'author_profile': 'https://Stackoverflow.com/users/4216954', 'pm_score': 5, 'selected': False, 'text': '<p>Simple example for reflection.\nIn a chess game, you do not know what will be moved by the user at run time. reflection can be used to call methods which are already implemented at run time:</p>\n\n<pre><code>public class Test {\n\n    public void firstMoveChoice(){\n        System.out.println("First Move");\n    } \n    public void secondMOveChoice(){\n        System.out.println("Second Move");\n    }\n    public void thirdMoveChoice(){\n        System.out.println("Third Move");\n    }\n\n    public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { \n        Test test = new Test();\n        Method[] method = test.getClass().getMethods();\n        //firstMoveChoice\n        method[0].invoke(test, null);\n        //secondMoveChoice\n        method[1].invoke(test, null);\n        //thirdMoveChoice\n        method[2].invoke(test, null);\n    }\n\n}\n</code></pre>\n'}, {'answer_id': 34149864, 'author': 'Marcus Thornton', 'author_id': 2288882, 'author_profile': 'https://Stackoverflow.com/users/2288882', 'pm_score': 4, 'selected': False, 'text': '<p>Reflection is to let object to see their appearance. This argument seems nothing to do with reflection. In fact, this is the "self-identify" ability.</p>\n\n<p>Reflection itself is a word for such languages that lack the capability of self-knowledge and self-sensing as Java and C#. Because they do not have the capability of self-knowledge, when we want to observe how it looks like, we must have another thing to reflect on how it looks like. Excellent dynamic languages such as Ruby and Python can perceive the reflection of their own without the help of other individuals. We can say that the object of Java cannot perceive how it looks like without a mirror, which is an object of the reflection class, but an object in Python can perceive it without a mirror. So that\'s why we need reflection in Java.</p>\n'}, {'answer_id': 35379881, 'author': 'Ravindra babu', 'author_id': 4999394, 'author_profile': 'https://Stackoverflow.com/users/4999394', 'pm_score': 3, 'selected': False, 'text': '<p>From java documentation <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/package-summary.html" rel="noreferrer">page</a></p>\n\n<blockquote>\n  <p><code>java.lang.reflect</code> package provides classes and interfaces for obtaining reflective information about classes and objects. Reflection allows programmatic access to information about the fields, methods and constructors of loaded classes, and the use of reflected fields, methods, and constructors to operate on their underlying counterparts, within security restrictions.</p>\n</blockquote>\n\n<p><code>AccessibleObject</code> allows suppression of access checks if the necessary <code>ReflectPermission</code> is available.</p>\n\n<p>Classes in this package, along with <code>java.lang.Class</code> accommodate applications such as debuggers, interpreters, object inspectors, class browsers, and services such as <code>Object Serialization</code> and <code>JavaBeans</code> that need access to either the public members of a target object (based on its runtime class) or the members declared by a given class</p>\n\n<p>It includes following functionality.</p>\n\n<ol>\n<li>Obtaining Class objects,</li>\n<li>Examining properties of a class (fields, methods, constructors),</li>\n<li>Setting and getting field values,</li>\n<li>Invoking methods,</li>\n<li>Creating new instances of objects.</li>\n</ol>\n\n<p>Have a look at this <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html" rel="noreferrer">documentation</a> link for the methods exposed by <strong><em><code>Class</code></em></strong> class.</p>\n\n<p>From this <a href="http://www.ibm.com/developerworks/library/j-dyn0603/" rel="noreferrer">article</a> (by Dennis Sosnoski, President, Sosnoski Software Solutions, Inc)  and this <a href="http://www.security-explorations.com/materials/se-2012-01-report.pdf" rel="noreferrer">article</a> (security-explorations pdf):</p>\n\n<p>I can see considerable drawbacks than uses of using Reflection</p>\n\n<p><strong><em>User of Reflection:</em></strong></p>\n\n<ol>\n<li>It provides very versatile way of dynamically linking program components</li>\n<li>It is useful for creating libraries that work with objects in very general ways</li>\n</ol>\n\n<p><strong><em>Drawbacks of Reflection:</em></strong></p>\n\n<ol>\n<li>Reflection is much slower than direct code when used for field and method access.</li>\n<li>It can obscure what\'s actually going on inside your code</li>\n<li>It bypasses the source code can create maintenance problems</li>\n<li>Reflection code is also more complex than the corresponding direct code</li>\n<li>It  allows violation of key Java security constraints such\nas data access protection and type safety</li>\n</ol>\n\n<p><strong><em>General abuses:</em></strong></p>\n\n<ol>\n<li>Loading of restricted classes,</li>\n<li>Obtaining references to constructors, methods or fields of a restricted class,</li>\n<li>Creation of new object instances, methods invocation, getting or setting field values of a restricted class.</li>\n</ol>\n\n<p>Have a look at this SE question regarding abuse of reflection feature:</p>\n\n<p><a href="https://stackoverflow.com/questions/1196192/how-do-i-read-a-private-field-in-java">How do I read a private field in Java?</a></p>\n\n<p><strong>Summary:</strong></p>\n\n<p><em>Insecure use of its functions conducted from within a system code can also easily lead to the compromise of a Java security mode</em>l. <strong><em>So use this feature sparingly</em></strong></p>\n'}, {'answer_id': 36877237, 'author': 'saumik gupta', 'author_id': 2774441, 'author_profile': 'https://Stackoverflow.com/users/2774441', 'pm_score': 3, 'selected': False, 'text': '<p>Reflection gives you the ability to write more generic code. It allows you to create an object at runtime and call its method at runtime. Hence the program can be made highly parameterized. It also allows introspecting the object and class to detect its variables and method exposed to the outer world.</p>\n'}, {'answer_id': 42945244, 'author': 'roottraveller', 'author_id': 5167682, 'author_profile': 'https://Stackoverflow.com/users/5167682', 'pm_score': 4, 'selected': False, 'text': '<p><strong>Reflection</strong> is an API which is used to examine or modify the behaviour of <em>methods, classes, interfaces</em> at runtime.</p>\n\n<ol>\n<li>The required classes for reflection are provided under <code>java.lang.reflect package</code>.</li>\n<li>Reflection gives us information about the class to which an object belongs and also the methods of that class which can be executed by using the object.</li>\n<li>Through reflection we can invoke methods at runtime irrespective of the access specifier used with them.</li>\n</ol>\n\n<p>The <code>java.lang</code> and <code>java.lang.reflect</code> packages provide classes for java reflection.</p>\n\n<p><strong>Reflection</strong> can be used to get information about –</p>\n\n<ol>\n<li><p><strong>Class</strong> The <code>getClass()</code> method is used to get the name of the class to which an object belongs.</p></li>\n<li><p><strong>Constructors</strong> The <code>getConstructors()</code> method is used to get the public constructors of the class to which an object belongs.</p></li>\n<li><p><strong>Methods</strong> The <code>getMethods()</code> method is used to get the public methods of the class to which an objects belongs.</p></li>\n</ol>\n\n<p>The <strong>Reflection API</strong> is mainly used in:</p>\n\n<p>IDE (Integrated Development Environment) e.g. Eclipse, MyEclipse, NetBeans etc.<br>\nDebugger and Test Tools etc.</p>\n\n<p><a href="https://i.stack.imgur.com/zEXW5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/zEXW5.png" alt=""></a></p>\n\n<p><strong>Advantages of Using Reflection:</strong></p>\n\n<p><em>Extensibility Features:</em> An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.</p>\n\n<p><em>Debugging and testing tools:</em> Debuggers use the property of reflection to examine private members on classes.</p>\n\n<p><strong>Drawbacks:</strong></p>\n\n<p><em>Performance Overhead:</em> Reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.</p>\n\n<p><em>Exposure of Internals:</em> Reflective code breaks abstractions and therefore may change behaviour with upgrades of the platform.</p>\n\n<p>Ref: <a href="http://www.geeksforgeeks.org/reflection-in-java/" rel="noreferrer">Java Reflection</a>  <a href="http://javarevisited.blogspot.in/2012/05/how-to-access-private-field-and-method.html" rel="noreferrer">javarevisited.blogspot.in</a></p>\n'}, {'answer_id': 43302409, 'author': 'Mohammed Sarfaraz', 'author_id': 4651104, 'author_profile': 'https://Stackoverflow.com/users/4651104', 'pm_score': 3, 'selected': False, 'text': '<p>As name itself suggest it reflects what it holds for example class method,etc apart from providing feature to invoke method creating instance dynamically at runtime.</p>\n\n<p>It is used by many frameworks and application under the wood to invoke services without actually knowing the code. </p>\n'}, {'answer_id': 53626477, 'author': 'BSeitkazin', 'author_id': 3631743, 'author_profile': 'https://Stackoverflow.com/users/3631743', 'pm_score': 2, 'selected': False, 'text': '<p>I want to answer this question by example. First of all <code>Hibernate</code> project uses <code>Reflection API</code> to generate <code>CRUD</code> statements to bridge the chasm between the running application and the persistence store. When things change in the domain, the <code>Hibernate</code> has to know about them to persist them to the data store and vice versa.</p>\n\n<p>Alternatively works <code>Lombok Project</code>. It just injects code at compile time, result in code being inserted into your domain classes. (I think it is OK for getters and setters)</p>\n\n<p><code>Hibernate</code> chose <code>reflection</code> because it has minimal impact on the build process for an application.</p>\n\n<p>And from Java 7 we have <code>MethodHandles</code>, which works as <code>Reflection API</code>. In projects, to work with loggers we just copy-paste the next code:</p>\n\n<pre><code>Logger LOGGER = Logger.getLogger(MethodHandles.lookup().lookupClass().getName());\n</code></pre>\n\n<p>Because it is hard to make typo-error in this case. </p>\n'}, {'answer_id': 55864747, 'author': 'cprn', 'author_id': 1347707, 'author_profile': 'https://Stackoverflow.com/users/1347707', 'pm_score': 2, 'selected': False, 'text': "<p>As I find it best to explain by example and none of the answers seem to do that...</p>\n\n<p>A practical example of using reflections would be a Java Language Server written in Java or a PHP Language Server written in PHP, etc. Language Server gives your IDE abilities like autocomplete, jump to definition, context help, hinting types and more. In order to have all tag names (words that can be autocompleted) to show all the possible matches as you type the Language Server has to inspect everything about the class including doc blocks and private members. For that it needs a reflection of said class.</p>\n\n<p>A different example would be a unit-test of a private method. One way to do so is to create a reflection and change the method's scope to public in the test's set-up phase. Of course one can argue private methods shouldn't be tested directly but that's not the point.</p>\n"}, {'answer_id': 64977871, 'author': 'RSG', 'author_id': 4704305, 'author_profile': 'https://Stackoverflow.com/users/4704305', 'pm_score': 0, 'selected': False, 'text': '<p><strong>IMPORTANT</strong></p>\n<p>Starting from Java 9 you can no longer use reflection, unless the package-info.java <strong>opens</strong> the module to reflection access.</p>\n<p>By default, &quot;reflection&quot; access is denied to all packages in the module.</p>\n<p>See <a href="https://www.oracle.com/corporate/features/understanding-java-9-modules.html" rel="nofollow noreferrer">Understanding Java 9 Modules</a></p>\n'}, {'answer_id': 70494517, 'author': 'Bhushan', 'author_id': 12965752, 'author_profile': 'https://Stackoverflow.com/users/12965752', 'pm_score': 1, 'selected': False, 'text': '<p>I am using reflection to create an object based on class name(class name in String) and call the method of that class</p>\n<pre><code>Object obj = Class.forName(config.getClassPath())\n                    .getDeclaredConstructor()\n                    .newInstance();\nMethod method = obj.getClass().getMethod(&quot;getCustomer&quot;, SearchObject.class, ObjectConfig.class,\n                HttpServletRequest.class);\nmethod.invoke(obj, searchObject, config, request);\n</code></pre>\n<p>But one major problem is that if you Autowired something on that class that will <strong>re-initialized to null</strong></p>\n'}]
['https://Stackoverflow.com/questions/37628', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/142/']