0. Instance Preparation
PackageCom.blueStarWei.invoke; Public classStudent {PrivateString name; PublicStudent () {} PublicStudent (String name) {Super(); This. Name =name; } Public voidsetName (String name) { This. Name =name; } PublicString GetName () {returnname; } @Override PublicString toString () {return"Student [name=" + name + "]"; }}
1. What is Reflection
Reflection is the information (such as interface information, member information, method information, and so on) that gets the type dynamically at run time (not at compile time), and then creates objects, accesses modify members, and invokes methods based on the information obtained.
2. How to get the class (3 types):
// mode one: Class.forName ("package name. Class name") Class stu1 = Class.forName ("com.blueStarWei.invoke.Student"); // Way two: Class name. class Class STU2 = Student. class ; // mode three: instance. GetClass () New Student (). GetClass ();
3. Create an Instance Object
Student Student = (Student) stu.newinstance ();
Note: 1) This method creates an instance by means of a non-parametric construct.
2) When you new an object, the class may not be loaded, and when you use the Newinstance () method, you must ensure that the class is loaded and connected "through Class.forName ()."
Class clazz = Class.forName ("com.blueStarWei.invoke.Student"= (Student) clazz.newinstance (); // equivalent to New Student ();
4. The effect of reflection
4.1 Determine the class to which any object belongs;
4.2 Determine the member variables and methods that any class has;
4.3 Methods for invoking arbitrary objects;
4.4 Constructs an object of any class;
4.5 Generate dynamic agent operations.
Basic concepts of Java Reflection