First, the basis of reflection
Java programs each Java class belongs to the same kind of thing, the Java class name that describes such things is class
For example, many people, using Java to represent the person class, a lot of classes, using Class,person class instance objects such as Zhang San, John Doe represents a specific people, and class class represents the various classes in memory byte code
A class is loaded into memory by the ClassLoader, it consumes a piece of storage space, the content of this space is the class bytecode, different classes of different bytecode, so their contents in memory is different, these spaces are represented by an object, these objects have the same type, the type is class
Interview question: Class.forName ("java.lang.String"), the role of forname ():
Returns a byte code in two ways: 1. This bytecode was once loaded and already exists in the JVM, so you can return directly. 2.JVM does not, with the class loader to load, after loading, byte code cache into the JVM, and then this bytecode will not need to load.
There are three ways to get the bytecode of a class:
1.string.class2.person p = new person (); P.getclass (); object. Class3.Class.forName ("java.lang.String");
Understanding: There are 9 predefined class objects, 8 basic types +void.class
The class instance object of the array type, Int[].class.isarray (); The byte code of an int array is an array
In summary: As long as the types that appear in the source program have their own class instance objects, int[], void
Demo:
<span style= "White-space:pre" ></span>public static void Main (string[] args) throws Exception {String str1 = " ABC "; Class Class1 = Str1.getclass (); Class class2 = String.class; Class CLASS3 = Class.forName ("java.lang.String"); System.out.println (CLASS1==CLASS2); System.out.println (CLASS2==CLASS3); System.out.println (Class1.isprimitive ());//Is the original type, False, which is class System.out.println (Int.class.isPrimitive ());// TrueSystem.out.println (Int.class==integer.class);//falsesystem.out.println (int.class==integer.type);// TrueSystem.out.println (Int[].class.isarray ());//true}
Second, understanding the concept of reflection
One classic Daniel summed up: Reflection is the mapping of the various components in the Java class into the corresponding Java classes.
A Java class is represented by an object of class class: constructors, methods, member variables, packages, etc. are also represented with Java classes, the car itself is a class, its tires, engines and so on are also a class. The class class in Java provides a series of methods to obtain information such as constructors, methods, member variables, and so on, which is the instance object of the corresponding class,Field, method, Contructor, package, and so on.
Each member of a class can be represented by an instance object of the corresponding reflection API class.
System.exit (0);
System.GC ();
System is a class
Exit, GC is also a class
Method Method1 on behalf of exit ()
METHOD2 representative GC ()
They all belong to the method class
This can also be a good understanding of Java's core idea: all things are objects. Whatever it is, it's all about the object.
Third, the application of reflection
1. Construction method
The constructor class represents a construction method in a class
Get all of the constructor methods for the class: constructor[] constructors = class.forname ("java.lang.String"). GetConstructors ();
Get a constructor method for the class: Constructor Constructor = Class.forName ("java.lang.String"). GetConstructor (Stringbuffer.class);
can also be: Constructor Constructor = String.class.getConstructor (Stringbuffer.class);
When acquiring an instance object, be aware that the type of the instance object is specified, because the compiler knows only that it is an object, but does not know what type of object it is, string str = (string) constructor.newinstance (New StringBuffer (" ABC "));
2. Member variables
The field class represents a member variable in a class
Note that Fiedx represents the definition of X, not the specific x variable, and to get the x variable, you must obtain it from the object.
public class Reflection {private int x;public int y;public Reflection (int x, int y) {super (); this.x = X;this.y = y;}} Import Java.lang.reflect.field;public class Lreanreflect {public static void main (string[] args) throws exception{ Reflection re = new Reflection (3, 4); Field Fieldy = Re.getclass (). GetField ("Y"); How much is//fieldy? 4? Wrong, Fieldy is not a variable on the object, but on the class, to use it to take the value on an object int st = (Integer) fieldy.get (re); System.out.println (ST);//x is a private field FIELDX = Re.getclass (). Getdeclaredfield ("x");//allow you to see, But don't let you use Fieldx.setaccessible (true);//violence reflex, whether it is with or without consent, I will use St = (Integer) fieldx.get (re); System.out.println (ST);}}
A comprehensive case of member variable reflection
Change the "B" in the string contents of the member variable of all string types in any object to "a"
import Java.lang.reflect.field;public class Lreanreflect {public static void main (string[] args) throws Exception {Reflection re Flection = new Reflection (3, 4); Changestringvalue (reflection); System.out.println (reflection);} private static void Changestringvalue (Object obj) throws exception{field[] fields = Obj.getclass (). GetFields (); for ( Field f:fields) {//if (F.gettype () equals (String.class))//Because there is only one copy of the byte Code of string if (F.gettype () ==string.class) {String str = (String) f.get (obj);//string value = Str.replaceall ("B", "a"); String value = str.replace (' B ', ' a '); F.set (obj,value);//update the changed value to Reflection}}}}package Reflectlearn;public class Reflection {private int x;public int y;public string str1 = "Ball";p ublic string str2 = "Basketball";p ublic string str3 = "Mail";p ublic Reflection (int x, int y) {super (); this.x = X;this.y = y;} @Overridepublic String toString () {return str1+ ":" +str2+ ":" +STR3;}}
3. Member Methods
(1) Calling method
method = String.class.getMethod ("CharAt", Int.class); String str1 = "abc"; System.out.println (Method.invoke (str1, 1));//invoke, call//If the Xxx.invoke (null,1) first parameter is NULL, then this method must be static because no object is required
(2) reflection of member methods that receive array parameters
Write a program that can execute the main method in the class based on the class name provided by the user .
import Java.lang.reflect.method;public class Lreanreflect {public static void main (string[] args) throws Exception {// Mymain.main (New string[]{"11", "22", "33"}); String Startingclassname = args[0];//You need to set the main parameter here, because I don't know to run the Main method//run as->run configurations->arguments ( Reflectlearn.mymain) System.out.println (startingclassname); Method Mainmethod = Class.forName (startingclassname). GetMethod ("main", String[].class); Mainmethod.invoke (NULL, new Object[]{new string[]{"11", "22", "33"});//package//mainmethod.invoke (NULL, (Object) New string[]{"11", "22", "33"});// Why Pack? The Main method takes a parameter (an array of strings) and we pass it to an array of strings//in JDK1.5 an array is the corresponding parameter, but in JDK1.4, each element in the array corresponds to a parameter//We pass a string[], That is, an object array, an open, where each element is a parameter, it will be considered to receive 3 parameters//So, with an object array, then hit a package, so I give you a bag of things, open, is an array, so OK//formally because, to be opened, So I'll give you a package in advance.}}class mymain{public static void Main (string[] args) {for (String S:args) {System.out.println (s);}}}
(3) reflection of the array
An array is also an object, each of the same element types, and an array of the same dimension, all of which are the same class
Import Java.lang.reflect.array;import Java.util.arrays;public class Lreanreflect {public static void main (string[] args ) throws Exception {int[] arr1 = new int[3];int[] arr2 = new int[4];int[][] Arr3 = new Int[3][4]; string[] Arr4 = new string[]{"A", "B", "C"}; System.out.println (arr1.getclass () = = Arr2.getclass ()); System.out.println (Arr1.getclass (). GetName ()); System.out.println (Arr1.getclass (). Getsuperclass (). GetName ()); Object obj1 = arr1;//object[] Obj2 = arr2; it's not working. object[] Obj3 = Arr3;object Obj4 = arr4;object[] Obj5 = ARR4; System.out.println (Arrays.aslist (arr1)); System.out.println (Arrays.aslist (ARR4));//string can be printelement (ARR1);} private static void Printelement (Object arr1) {Class c = arr1.getclass (); if (C.isarray ()) {int len = array.getlength (arr1); for (int i = 0;i<len;i++) {System.out.println (Array.get (Arr1,i));}} Else{system.out.println (ARR1);}}}
Extension: About Hashcode
When an object is stored in the HashSet collection, it is not possible to modify the fields in the object that participate in the hash value, otherwise the object's modified hash value differs from the hash value originally stored in the Hasgset collection. This causes the contains of the current collection object to be used to examine the modified object, which results in a failed retrieval, resulting in the inability to remove the pre-modified object from the HashSet collection, thereby causing a memory leak
public class Reflection {private int x;public int y; @Overridepublic int hashcode () {final int prime = 31;int result = 1;re Sult = Prime * result + X;result = Prime * result + Y;return result;} @Overridepublic boolean equals (Object obj) {if (this = = obj) return true;if (obj = = null) return False;if (GetClass ()! = obj . GetClass ()) return false; Reflection other = (Reflection) obj;if (x! = other.x) return false;if (Y! = other.y) return False;return true; public Reflection (int x, int y) {super (); this.x = X;this.y = y;}} public class ReflectTest2 {public static void main (string[] args) {Collection concollection = new HashSet (); Reflection[] rs = new reflection[]{new Reflection (3, 3), New Reflection (4, 4), New Reflection (3, 3)};for (Reflection R:rs) c Oncollection.add (r);//rs[0].y = 1; System.out.println (Concollection.contains (rs[0])); Boolean B = Concollection.remove (rs[0]); System.out.println (b); System.out.println (Concollection.size ());}} Truetrue1 Open the note falsefalse2
So, if we save the object in the collection, change the object, then delete the object, the object is not deleted, and the memory leaks. So save it in a centralized object, and don't
Modified the
The concept of frame and the principle of developing frame with reflective technology
Realization framework of the function of reflection
Simulate an ultra -Small Frame
Config.propertiesclassname=java.util.arraylistpublic class Reflection {private int x;public int y;public Reflection ( int x, int y) {super (); this.x = X;this.y = y;}} public class ReflectTest2 {public static void main (string[] args) throws Exception {InputStream in = new FileInputStream (" D:/javasourue/config.properties "); Properties Pro = new properties ();//From the configuration file, Get what Class pro.load (in); In.close (); String className = Pro.getproperty ("ClassName"); Collection concollection = (Collection) class.forname (className). newinstance (); Reflection[] rs = new reflection[]{new Reflection (3, 3), New Reflection (4, 4), New Reflection (3, 3)};for (Reflection R:rs) c Oncollection.add (R); System.out.println (Concollection.size ());}}
Framework:
A blank room is a frame, and users themselves decorate doors, windows, etc., the user is using frames, doors and windows inserted into the frame
The difference between a framework and a tool class is that the tool class is called by the user, and the framework invokes the class provided by the user
The framework solves the problem:
Real estate Developers in the building (frame), may not buy a house, nature will not think of decoration, then the framework how to call the user later write class?
Because when you write a frame, there is no way to know what class to call later, you cannot new object, so you have to use reflection to solve this problem.
A deeper understanding of reflection in Java