ArticleDirectory
- Class
- Class applications
- Get the class structure
- Reflection Application
When I first started learning Java, it was really hard to understand what reflection was.
Some books, even classic ones, are confusing. Maybe I am too stupid.
Moreover, the Internet says that reflection mechanisms need to be applied frequently in the future of learning frameworks, which will make people feel a little uneasy.
By accident, I saw some of the sections and videos that explained reflection, and thought I could understand it.
Now, I decided to write and read all the main content and operations.
I think, for me such a stupid person, the best way to learn may be to keep repeating.
When I encountered something I didn't understand, I stopped and learned it again. Although it took a lot of time, it also worked on me.
In my understanding, reflection is used to restore the complete information of a Class Based on an instantiated object.
At least for me, I think the benefit it brings to me is that it makes me understand object-oriented again from the bottom up.
X_x hated the thick heads here and killed my brain cells.
Class
To complete reflection, you must understand the class
Instance 1: Get the package name and class name through the object
Package Org. siu; Class test {} public class demo {public static void main (string [] ARGs) {test T = new test (); system. out. println (T. getclass (); system. out. println (T. getclass (). getname ());}}
The compilation result is as follows. Pay attention to the package compilation method.
The getclass () method here is inherited from the object class by default.
In Java, the object class is the parent class of all classes. Similarly, the instantiated object of all classes is also an instance of the class.
Therefore, this will involve the concepts of upward and downward transformation.
Due to the insecure factor of the downward transformation, the wildcard type will also come soon.
(But what I want to say is that the generic design here is very dazzling! Nima, the whole Java syntax design is equally eye-catching and super disgusting !!!)
Instance 2: Class class instantiation
Because the class does not have a constructor method, there are three methods to instantiate the class:
- Object. getclass ()
- Class. Class
- Forname ()
Class test {} public class demo {public static void main (string [] ARGs) {// Method 1: Test T = new test (); Class <? Extends test> C1 = T. getclass (); system. out. println (C1); // Method 2: // to avoid special characteristics, the test class is not used here, but the string class in the Java library <string> C2 = string. class; system. out. println (C2); // method 3: // The forname () method throws an exception class <?> C3 = NULL; try {C3 = Class. forname ("test");} catch (classnotfoundexception e) {e. printstacktrace ();} system. out. println (C3 );}}
Among them, the forname () method needs to be focused on, because it can instantiate the class in case of class uncertainty, more flexibility
Class applications
The class has a method called newinstance (), which can be used to create a new instance of a Class Object.
What should I do? The class object contains the reflected class. We need to construct a new instance of the class (new object)
Instance 3: Class class construction object without Parameters
Public class demo {public static void main (string [] ARGs) {// instantiate the class object. The forname () method throws an exception class <?> C = NULL; try {// The complete package name and class name c = Class are required here. forname ("Java. lang. string ");} catch (classnotfoundexception e) {e. printstacktrace () ;}// generate a string reference string S = NULL; try {// convert the constructed object to the string class downward // newinstance () method will throw an exception S = (string) C. newinstance ();} catch (instantiationexception e) {e. printstacktrace ();} catch (illegalaccessexception e) {e. printstacktrace ();} system. out. println ("String Length:" + S. length ());}}
In this way, a new object is constructed in the form of no parameters, as in normal mode
The same way to construct a new object using the no-argument Constructor
We know that in addition to the parameter constructor, there will be parameter constructor in the class.
In reflection, how can we construct objects in the form of parameters? See
Example 4: A Class Object with Parameters
Import java. Lang. Reflect. constructor; public class demo {// The following methods throw too many exceptions,CodeThe public static void main (string [] ARGs) throws exception {class <?> C = NULL; try {c = Class. forname ("Java. lang. string ");} catch (classnotfoundexception e) {e. printstacktrace ();} Char [] CH = {'h', 'E', 'l', 'l', 'O'}; string S = NULL; // obtain the construction method of the Class Object with parameters. The parameters in the brackets are written as follows: type. classconstructor <?> Con = C. getconstructor (char []. class); // use this constructor to construct a new String object. The parameter is a char array S = (string) con. newinstance (CH); system. out. println ("constructed string:" + S );}}
We still use the string class as an example, because the string class is mostly used for ease of understanding.
Note that the constructor () method must be used to obtain the constructor.
The parameter type is: original type. Class
Another point is that the constructor used here must exist in the original class, whether there are parameters or no parameters.
So, how can we know the constructor, common method, inherited parent class and other details in the original class? See
Get the class structure
To obtain the class structure through reflection, we need to import a new package java. Lang. reflect.
Example 5: Get the class Constructor
Import Java. lang. reflect. constructor; import Java. util. arrays; public class demo {// The following several methods throw too many exceptions. For the sake of code closeness, the public static void main (string [] ARGs) is directly thrown to the virtual machine) throws exception {class <?> C = NULL; try {c = Class. forname ("Java. lang. boolean ");} catch (classnotfoundexception e) {e. printstacktrace ();} // The getconstructors () method returns a constructor array constructor <?> [] Cons = C. getconstructors (); // you can write it by yourself. For convenience, I use arrays. tostring. out. println (arrays. tostring (cons ));}}
I chose the Boolean class as an example, because the Boolean class has two constructor methods for ease of reading.
Instance 6: Obtain the interface implemented by the class
Import java. util. arrays; public class demo {public static void main (string [] ARGs) throws exception {class <?> C = NULL; try {c = Class. forname ("Java. Lang. boolean");} catch (classnotfoundexception e) {e. printstacktrace ();} class <?> [] In = C. getinterfaces (); system. Out. println (arrays. tostring (in ));}}
There's nothing to say. Check the results.
Instance 7: Obtain the parent class
Public class demo {public static void main (string [] ARGs) throws exception {class <?> C = NULL; try {c = Class. forname ("Java. lang. boolean ");} catch (classnotfoundexception e) {e. printstacktrace ();} // note that it will not be an array, why? Class <?> Su = C. getsuperclass (); system. Out. println (SU );}}
Don't forget, in Java, it is a single inheritance, and the parent class has only one
Instance 8: obtain all methods of the class
Import java. Lang. Reflect. method; public class demo {public static void main (string [] ARGs) throws exception {class <?> C = NULL; try {c = Class. forname ("Java. lang. boolean ");} catch (classnotfoundexception e) {e. printstacktrace ();} method [] M = C. getmethods (); // Well, this time I will write a print list in great mercy for (INT I = 0; I <m. length; I ++) {system. out. println (M [I]) ;}}
Take a part and look at it ...... These examples are relatively simple.
Instance 9: Get all attributes of this class
Import Java. lang. reflect. field; class person {private string name; private int age;} public class demo {public static void main (string [] ARGs) throws exception {class <?> C = NULL; try {c = Class. forname ("person");} catch (classnotfoundexception e) {e. printstacktrace ();} field [] f = C. getdeclaredfields (); For (INT I = 0; I <F. length; I ++) {system. out. println (F [I]) ;}}
The getdeclaredfielsd () method can obtain all attributes. getfields () can only obtain public attributes.
Instance 10: Get the attribute value in this class
Import Java. lang. reflect. field; class person {public string name; private int age; Public Person (string name, int age) {This. name = Name; this. age = age ;}} public class demo {public static void main (string [] ARGs) throws exception {person P = new person ("zhangsan", 12); Class <?> C = P. getclass (); // obtain the value of the public attribute field F1 = C. getfield ("name"); // get (p) indicates the object to be retrieved. String STR = (string) f1.get (p); system. out. println ("name:" + Str); // obtain the Private Attribute Value Field F2 = C. getdeclaredfield ("Age"); // age is a private attribute, so set the security check to truef2.setaccessible (true); int age = (INT) f2.get (p); system. out. println ("Age:" + age );}}
Note that the setaccessible () method can be used to set whether to access and modify private attributes.
Frankly speaking, I haven't found any things that can highlight my titanium eye in Java.
Every time I write a bunch of tedious syntaxes to implement a little trick, or I will call the API desperately and throw exceptions.
Makes code that is not compact enough more cumbersome.
If I like a language, before using it to make things, its own characteristics must be able to impress me
Obviously, Java does not make me happy, maybe a lotProgramLike me, I was forced to use Java.
Just to appease my lonely coding heart, let's take a look at the content below
Reflected application instance 11: modifying attributes through reflection
Import Java. lang. reflect. field; class person {private string name; Public Person (string name) {This. name = Name;} Public String tostring () {return "name:" + this. name ;}} public class demo {public static void main (string [] ARGs) throws exception {person P = new person (""); system. out. println (p); Class <?> C = P. getclass (); // defines the attribute field F = C. getdeclaredfield ("name"); F. setaccessible (true); // modify attributes and input the object and value F. set (P, "Zhang 'er egg"); system. out. println (p );}}
Several methods are related. If you cannot understand them, familiarize yourself with the above examples.
Example 12: Call the method through reflection
Import Java. lang. reflect. method; class person {public void print (int I) {system. out. println ("I'm writing a number:" + I);} public static void say (string Str) {system. out. println ("I'm talking about:" + Str) ;}} public class demo {public static void main (string [] ARGs) throws exception {person P = new person (); class <?> C = P. getclass (); // The method name required for the getmethod () method, and the parameter type method M1 = C. getmethod ("print", Int. class); // invoke () indicates the call meaning, and the object and parameter m1.invoke (p, 10) need to be input; Method m2 = C. getmethod ("say", String. class); // null indicates that the object cannot be called, that is, the static method m2.invoke (null, "");}}
Here we demonstrate a common method with parameters and a static method.
Since all the parameters are written out, it is easier to have no parameters. Just pass in an object directly.
Instance 13: operate arrays through reflection
Import Java. lang. reflect. array; public class demo {public static void main (string [] ARGs) throws exception {int [] arr = {1, 2, 3, 4, 5}; Class <?> C = arr. getclass (). getcomponenttype (); system. out. println ("array type:" + C. getname (); int Len = array. getlength (ARR); system. out. println ("array length:" + Len); system. out. print ("traversal array:"); For (INT I = 0; I <Len; I ++) {system. out. print (array. get (ARR, I) + "");} system. out. println (); // modify the array system. out. println ("the first element before modification:" + array. get (ARR, 0); array. set (ARR, 0, 3); system. out. println ("the first modified element:" + array. get (ARR, 0 ));}}
Note that getcomponenttype () returns the class of the array element.
I have written so much for the time being. In my books, there are also applications of reflection in the factory model.
It's nothing more than replacing it with the forname () method.
I am a beginner in Java. I hate Java's disgusting syntax and design.
This is for Android, to lay the foundation, to adapt to future work
Fuck Java ......