Summary and Analysis Based on java reflection

Source: Internet
Author: User

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
Copy codeThe Code is as follows: 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 instantiation

Because the Class does not have a constructor method, there are three methods to instantiate the Class:

Object. getClass ()
Class. Class
ForName ()
Copy codeThe Code is as follows: 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 particularity, the Test class is not used here, but the String class in the java library is used
Class <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 construction object without ParametersCopy codeThe Code is as follows: 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 are required.
C = Class. forName ("java. lang. String ");
} Catch (ClassNotFoundException e ){
E. printStackTrace ();
}

// Generate a string reference
String s = null;
Try {
// Convert the constructed object down to the String class
// The newInstance () method throws 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
Copy codeThe Code is as follows: import java. lang. reflect. Constructor;

Public class Demo {
// The following methods throw too many exceptions. In order to compact the code, it is directly thrown to the virtual machine.
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. class
Constructor <?> 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
Copy codeThe Code is as follows: import java. lang. reflect. Constructor;
Import java. util. Arrays;

Public class Demo {
// The following methods throw too many exceptions. In order to compact the code, it is directly thrown to the virtual machine.
Public static void main (String [] args) 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 the print method by yourself. To make it easier for me to use Arrays. toString ()
System. 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
Copy codeThe Code is as follows: 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
Copy codeThe Code is as follows: 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
Copy codeThe Code is as follows: 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 wrote a print list with great compassion.
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
Copy codeThe Code is as follows: 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
Copy codeThe Code is as follows: 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 public Attribute Value
Field f1 = c. getField ("name ");
// Get (p) indicates the value of the object to be obtained
String str = (String) f1.get (p );
System. out. println ("name:" + str );

// Obtain the value of the private property
Field f2 = c. getDeclaredField ("age ");
// Age is a private property, so you must set the security check to true.
F2.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 many programmers are forced to use java like me.

Just to appease my lonely coding heart, let's take a look at the content below

Reflected application instance 11: modifying attributes through reflection
Copy codeThe Code is as follows: 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 ();

// Define the attributes to be modified
Field f = c. getDeclaredField ("name ");
F. setAccessible (true );
// Modify attributes and input the object and value to be set
F. set (p, "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
Copy codeThe Code is as follows: 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 saying:" + str );
}
}

Public class Demo {
Public static void main (String [] args) throws Exception {
Person p = new Person ();
Class <?> C = p. getClass ();

// The getMethod () method must be passed in the method name and parameter type.
Method m1 = c. getMethod ("print", int. class );
// Invoke () indicates the call meaning, and the object and parameter need to be passed in
M1.invoke (p, 10 );

Method m2 = c. getMethod ("say", String. class );
// Null indicates that the object cannot be called, that is, the static method.
M2.invoke (null, "Your sister ");
}
}

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
Copy codeThe Code is as follows: 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 ("traversing 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.