Today, I learned some Java reflection mechanisms and made a simple record.
In my understanding, some object-related information is obtained during running:
- The "class" type of the object, which member variables, which methods, value of member variables, and the creation of an object of a class;
Currently, I can think of some application scenarios:
- Various Objects (no matter the subclass, parent class, or any implementation of the Interface) are thrown in, explicitly calling their methods, etc., regardless of their internal implementation. "Throw in, adjust, treat equally, and personalize"
- For an object, "Create a counterfeit product", that is, a new type object (Object array, etc );
- Break through the class's access permission control on objects/methods, and break through encapsulation (accessible private variables and methods), which is very pornographic and violent;
[1] obtain the "class" Type
Class <?> Classtype = Class. forname ("Java. Lang. String ");
Class <?> Classtype = mytest. Class;
Class <?> Classtype = object. getclass ();
[2] constructor, which constructs objects of classes with parameters;
Constructor cons = classtype. getconstructor (new class [] {});
Object o = cons. newinstance (new object [] {});
If the parameter is not included, you can directly write it like this:
Object o = classtype. newinstance ();
Extra-curricular small expansion (creating a class object with parameters ):
Class [] argsclass = new class [args. Length]; // creates a Class Based on Object [] ARGs
For (INT I = 0; I <args. length; I ++ ){
Argsclass [I] = ARGs [I]. getclass ();
}
Constructor cons = classtype. getconstructor (argsclass); // obtain the constructor with this parameter type
Cons. newinstance (ARGs); // input an object and create an object
[3] member variables
Field [] fields = classtype. getdeclaredfields ();
Field field = classtype. getdeclaredfield (O );
Field. Get (O );
Fileld. Get (classtype); // static member of the class.
Field. getname ();
Field. GetType ();
[4] Method
Method [] Methods = classtype. getdeclaredmethods ();
Method method = classtype. getmethod ("add", new class [] {Int. Class, Int. Class });
Methods. setaccessible (true); // too violent
Object result = method. Invoke (O, new object [] {1, 2 });
Object result = method. Invoke (null, new object [] {1, 2}); // executes the static method
[5] dynamic array
Object arr = array. newinstance (classtype, 10 );
Array. Set (ARR, 1, "hello ");
String STR = (string) array. Get (ARR, 1 );
Int [] dims = new int [] {5, 10, 15 };
Object arr = array. newinstance (integer. type, 3 );
Object arrobj = array. Get (ARR, 3); // obtain a [3] 2D array [10] [15]
Object arrobj2 = array. Get (arrayobj, 5); // obtain a group of arrays [5] [15]
Array. setint (arrayobj2, 10, 37); // set the 10th values to 37.
Int [] [] [] arraycast = (INT [] [] []) Arr;
System. Out. println (arraycast [3] [5] [10]);
[6] whether it is an instance of a class
Someclass. isinstance (OBJ );