What is reflection. What is the use of reflection. 1. What is reflection.
Reflection (Reflection) enables programs that run in the JVM to detect and modify run-time behavior. "This concept is often confused with introspection (introspection), and here is the interpretation of the two terms in Wikipedia: Introspection is used to detect the type of an object and the attributes it contains at run time; reflection is used to detect and modify the structure and behavior of an object at run time.
As can be seen from their definition, introspection is a subset of reflection. Some languages support introspection, but do not support reflection, such as C + +.
Introspection Example: The instanceof operator is used to detect whether an object belongs to a particular class.
1 2 3 4 |
if (obj instanceof Dog) {Dog d = (Dog) obj; D.bark (); } |
Reflection Example: the Class.forName () method can get the corresponding class object from the name of the class or interface (a string or fully qualified name). The Forname method triggers the initialization of the class.
1 2 3 4 5 |
Use reflection class<?> C = Class.forName ("Classpath.and.classname"); Object dog = C.newinstance (); Method m = C.getdeclaredmethod ("Bark" |