1 What is the reflection mechanism?
The reflection mechanism is in the running state, for any class, can know all the properties and methods of this class, for any one object, can call any of its methods and properties; This dynamically acquired information and the ability to dynamically invoke the method of the object is called the reflection mechanism of the Java language.
In the object-oriented world, everything is the object. In the Java language, static members, ordinary data types are not objects?
Who is the object of the class?
The first class is an object, and the class is an instance object of the Java.lang.Class class.
Create a new Foo class
Foo This class is also an instance object, which is an instance object of class, which is called (class type) on the official website.
Reflection is one of the features of the Java programming language that allows a running Java program to get its own information and manipulate properties within a class or object.
The core of reflection is that the JVM dynamically loads a class or invokes a method/access property at run time, and it does not need to know who is running the object in advance (write code or compile time).
Understanding reflection actually requires an understanding of the JVM, but the general data does not refer to the JVM in this section, after all, learning is also going from shallow to deep.
2 What the reflection mechanism can do
The reflection mechanism mainly provides the following functions:
Determine the class to which any object belongs at run time;
Constructs an object of any class at run time;
Determine the member variables and methods of any class at run time;
A method of invoking any object at run time;
Generates a dynamic agent.
Note that it is run-time fetching instead of compile-time. In fact, many times we write code directly with eclipse ignoring the process of compiling.
At Eclipse, when we enter a point (such as a.) The compiler will automatically list its properties and methods, and this will use the reflection
3 The correlation API of the reflection mechanism (in this case only the first two of the five functions of the reflection mechanism)
The implementation of the reflection mechanism of Java has to be aided by 4 classes: Class,constructor,field,method;
Get the full package name and class name from an object
Package Cn.xins08.boke;public class Testreflect {public static void main (string[] args) {Testreflect testrefle ct = new Testreflect (); System.out.println (Testreflect.getclass (). GetName ()); Results: Cn.xins08.boke.TestReflect}}
Instantiate a Class object:
There are three ways to implement a reflection mechanism to get a class:
package cn.xins08.boke;public class testreflect { public Static void main (String[] args) throws Exception { Class<?> class1 = null; Class<?> class2 = null; class<?> class3 = null; //The first way (this method is commonly used in JDBC development to load data-driven) class1 = class.forname ("Cn.xins08.boke.TestReflect") ; //the Third way: Any object in Java has a GetClass method class2 = new testreflect (). GetClass (); //the third way any object in Java has a class attribute class3 = testreflect.class; system.out.println ("Class name: " + class1.getname ()); system.out.println ("Class name: " + class2.getname ()); system.out.println ("Class name: " + class3.getname ()); // printing results: /* * class name: cn.xins08.boke.testreflect class name: cn.xins08.boke.testreflect class name: * cn.xins08.boke.TestReflect */ }}
Gets the parent class of an object with the implemented interface:
package cn.xins08.boke;import java.io.serializable;public class testreflect Implements serializable { private static final long serialversionuid = -2862585049955236662l; public static void main (String[] args) throws Exception { Class<?> clazz = Class.forName ("Cn.xins08.boke.TestReflect"); // Get parent class class<?> parentclass = clazz.getsuperclass (); system.out.println ("Clazz's parent class is:" + Parentclass.getname ()); // clazz's parent class is: java.lang.object // get all the interfaces class<?> intes[] = clazz.getinterfaces (); System.out.println ("Clazz implements the interface is:"); for (int i = 0; i < intes.length; i++) { system.out.println ((i + 1) + " : " + intes[i].getname ()); } // clazz implements an interface with: // 1:java.io.Serializable }}
To create an instance:
There are two main ways to generate objects by reflection:
(1) Use the Newinstance () method of the class object to create an instance of the class object counterpart.
class<?> c = String.class;object str = c.newinstance ();
Initializes a class, what is the difference between New and newinstance () when an instance is generated?
The difference is that the object is created in a different way, the former is using the class loading mechanism, then why there are two ways to create objects? This needs to be explained in terms of scalable, extensible, reusable software.
Newinstance: Weak type. Low efficiency. Only parameterless constructs can be called.
NEW: Strongly typed. relatively efficient. Can invoke any public construct.
Newinstance () is an inevitable choice for the implementation of IOC, reflection, interface programming and dependency inversion, and new can only be instantiated for specific classes, not suitable for interface programming.
(2) First obtains the specified constructor object through the class object, and then calls the constructor object's Newinstance () method to create the instance. This method allows you to construct an instance of the class with the specified constructor.
Gets the Class object that corresponds to String class<?> c = string.class; Gets a string class with a string argument to the constructor Constructor Constructor = C.getconstructor (String.class); Creates an instance of Object obj = constructor.newinstance ("23333") according to the constructor; System.out.println (obj);
Note: Reflection consumes a certain amount of system resources, and if you do not need to create an object dynamically, you do not need to use reflection
At the end of the article we discuss the factory model:
Package Cn.xins08.boke;public interface Fruit {public void eat ();
Package Cn.xins08.boke;public class Apple implements fruit{public void Eat () {System.out.println ("Eat apple"); } }
Package Cn.xins08.boke;public class Factory {public static Fruit getinstance (String className) {if ("Apple". Equals (class Name) {return new Apple (); } return null;}}
Package Cn.xins08.boke;public class Factorydemo {public static void main (string[] args) {Fruit F = factory.get Instance ("Apple"); F.eat (); }}//returned the result is "eat apples"
This is one of the simplest factory design patterns, but one big problem is that if the subclass of the interface now increases, then the factory class will need to be changed. The cause of this problem is new, which is different if it becomes a reflection mechanism. The materialized object of reflection needs only the package. The class is ready.
Package Cn.xins08.boke;public interface Fruit {public void eat ();
Package Cn.xins08.boke;public class Orange implements fruit{public void Eat () {System.out.println ("eat oranges"); } }
Package Cn.xins08.boke;public class Apple implements fruit{public void Eat () {System.out.println ("Eat apple"); } }
Package Cn.xins08.boke;public class Factory {public static Fruit getinstance (String className) {Fruit Fruit = null;try{ Here is the class type of fruit, which does coercion type conversion fruit = (fruit) class.forname (className). newinstance (); } catch (Exception e) {e.printstacktrace (); } return F; } }}
Package Cn.xins08.boke;public class Factorydemo {public static void main (string[] args) {Fruit F = factory.get Instance ("Cn.xins08.boke.Apple"); F.eat (); }}
At this point we find that even if you add a subclass of several interfaces, the factory class can still perform the instantiation of the object, which can correspond to all the changes.
So far you've had the most basic reflection used, before you learn spring, and so on, after learning spring's dependency injection, inversion control, I believe there will be a better understanding of reflection.
About the reflection of the following functions, and so on after writing will be added in this article link
Determine the member variables and methods of any class at run time;
A method of invoking any object at run time;
Generates a dynamic agent.
--java 10,000 hours into the road of God-this first and 51CTO blog---
Recent reading Plans:
"Thinking, fast and slow"
The peak of the tide
This article is from the "xinsz08の parallel space-time" blog, be sure to keep this source http://xinsz08.blog.51cto.com/10565212/1946912
A detailed Java reflection mechanism