Home>

First, the knowledge that needs to be mastered beforehand (java virtual machine)

Java virtual machine method area:

The java virtual machine has a runtime data area,This data area is divided into method areas,Heap area and stack area,The main thing we need to know here is the method area.The main function of the method area is to store the type information of the loaded class.When the Java virtual machine loads a certain type,The class loader needs to locate the corresponding class file, and then read it into the java virtual machine.Immediately after the virtual machine extracts the type information in the class,This information is stored in the method area.This information mainly includes:

1.The fully qualified name of this type

The fully qualified name of the direct superclass of this type

3. Is this type a class type or an interface type?

4, this type of access modifier

5.An ordered list of the fully qualified names of any direct superinterfaces

6, the constant pool of this type

Field information

8.Method information

9.All class variables except constants

10.A reference to the class

Wait (readers can refer to the book "Deep Java Virtual Machine" narrative)

class:

The class class is a very important Java basic class. Whenever a new type is loaded,The java virtual machine will create a class instance corresponding to the new type in the java heap, and this instance represents this type.Through the class instance, we can access the basic information of the type.As mentioned above, the type information of a loaded class is stored in the method area.We can access this information through class instances.For example, there are corresponding methods for the information classes mentioned above.as follows:

1, getname ();the fully qualified name of this type

2, getsuperclass ();the fully qualified name of the direct superclass of this type

3. isinterface ();is this type a class type or an interface type

4, gettypeparamters ();access modifiers for this type

5. getinterfaces ();an ordered list of the fully qualified names of any direct superinterfaces

6, getfields ();field information

7, getmethods ();method information

Wait (readers can refer to the jdk help documentation,Get more info)

Second, java reflection

The concept of reflection:The so-called reflection is that the Java language has a self-seeking ability at runtime,Reflection enables your program code to get internal information about classes loaded into the jvm,Allows you to get the internal information of the required class when executing the program,Instead of having to know the internal information of the required class when writing code,This makes reflection the primary tool for building flexible applications.

Common reflection classes and functions:The implementation of the Java reflection mechanism depends on four classes:class, constructor, field, method;where class represents a class object,constructor-the constructor object of the class,field-the attribute object of the class,method-the method object of the class,Through these four objects we can roughly see the various components of a class.The core of which is the class class, which is the basis for implementing reflection.The methods it contains have already been explained in the first part.When we apply reflection, we usually care about the constructors, properties, and methods of a class.Below we mainly introduce the methods for these three elements in the class:

1, the method to get the constructor

constructor getconstructor (class [] params)-get a public constructor using a special parameter type,

constructor [] getconstructors ()-get all public constructors of a class

constructor getdeclaredconstructor (class [] params)-get a constructor that uses a specific parameter type (regardless of access level)

constructor [] getdeclaredconstructors ()-get all constructors of a class (regardless of access level)

2. Method for obtaining field information

field getfield (string name)-get named public field

field [] getfields ()-get all public fields of the class

field getdeclaredfield (string name)-get the named field of the class declaration

field [] getdeclaredfields ()-get all fields declared by the class

3.Methods for obtaining method information

method getmethod (string name, class [] params)-use a specific parameter type,Get named public method

method [] getmethods ()-get all public methods of the class

method getdeclaredmethod (string name, class [] params)-use close parameter types,Get named method of class declaration

method [] getdeclaredmethods ()-get all methods declared by a class

Basic steps to apply reflection:

1. Get the class object of the class i want to operate;

Method 1:classc=class.forname ("java.lang.string")

Method 2:For basic data types, you can use statements such as class c=int.class or class c=integer.type

Method 3:class c=myclass.class

2. Call the methods in the class to get the information set i want,Such as calling getdeclaredfields () method to get all properties of the class;

3. Process the information obtained in step 2,Then do what i want to do.

Reflection example:

Below I will give three examples of class constructors, properties, and methods.Demonstrate the application process of reflection.

Constructor

The steps are:get the constructor of a class through the reflection mechanism,Then call the constructor to create an instance of the class

import java.lang.reflect. *;
public class constructordemo {
  public constructordemo () {}
  public constructordemo (int a, int b) {
   system.out.println ("a =" + a + "b =" + b);
  }
  public static void main (string args []) {
    try {
      class cls=class.forname ("package name.constructordemo");
      class partypes []=new class [2];partypes [0]=integer.type;
      partypes [1]=integer.type;
      constructor ct=cls.getconstructor (partypes);
      object arglist []=new object [2];
      arglist [0]=newinteger (37);
      arglist [1]=newinteger (47);
      object retobj=ct.newinstance (arglist);
     } catch (throwable e) {
      system.err.println (e);}
     }
  }

Properties

The steps are:obtaining a certain attribute of a certain class through a reflection mechanism,Then change the value of this property corresponding to an instance of this class

import java.lang.reflect. *;
public class fielddemo1 {
 public double d;
 public static void main (string args []) {
 try {
  class cls=class.forname ("fielddemo1");
  field fld=cls.getfield ("d");
  fielddemo1 fobj=new fielddemo1 ();
  system.out.println ("d =" + fobj.d);
  fld.setdouble (fobj, 12.34);
  system.out.println ("d =" + fobj.d);
 } catch (throwable e) {
  system.err.println (e);}
 }
}

3.Method

The steps are:get a method of a certain class through the reflection mechanism,Then call this method corresponding to an instance of this class

//Call the method by using its name
import java.lang.reflect. *;
public class methoddemo1 {
 public int add (int a, int b) {
 return a + b;
 }
 public static void main (string args []) {
  try {
   class cls=class.forname ("methoddemo1");
   class partypes []=new class [2];
   partypes [0]=integer.type;
   partypes [1]=integer.type;
   method meth=cls.getmethod ("add", partypes);
   methoddemo1 methobj=new methoddemo1 ();
   object arglist []=new object [2];
   arglist [0]=new integer (37);
   arglist [1]=new integer (47);
   object retobj=meth.invoke (methobj, arglist);
   integer retval=(integer) retobj;
   system.out.println (retval.intvalue ());
  } catch (throwable e) {
   system.err.println (e);
  }
 }
}

Third, the application of java reflection (hibernate)

We gave a more systematic explanation of java reflection in the second part,A few simple examples are also given,Let's discuss the specific application of Java reflection.As we already know, the Java reflection mechanism provides a versatile method for dynamically linking program components.It allows programs to create and control objects of any class (based on security restrictions) without having to hardcode the target class in advance.These features make reflection particularly suitable for creating libraries that work with objects in a very general way.For example, reflection is often used in frameworks that persistently store objects as databases, xml, or other external formats.Below we have taken the hibernate framework as an example to explain the significance of reflection.

Hibernate is a java framework that shields jdbc and implements ORM. Using this framework, we can discard tedious SQL statements and use the save () method of the session class in hibernate to directly store objects of a certain class into the database.That is, the code that hibernate involved in the SQL statement helped us do.At this time, a problem appeared,How does hibernate know what properties an object has to store?What kind of properties are these?So, how should it construct the sql statement when storing the object attributes in the database?The weapon to solve this problem is our java reflection!

Let ’s take an example to illustrate,For example, we define a user class. There are 20 attributes in the user class and the get and set methods of these attributes. Correspondingly, there is a user table in the database. This user table corresponds to 20 fields. Suppose we extract a record from the user table,Now you need to assign the contents of the 20 fields of this record to the 20 attributes of a user object myuser, and the hibernate framework does not know this user class when compiling. He cannot directly call myuser.getxxx or myuser.setxxx , Reflection is used at this time,The specific process is as follows:

1. Construct a preparedstament statement according to the query conditions, which returns the values ​​of 20 fields;

2. Hibernate reads the configuration file to obtain the attribute list of the user class (a string array) and the types of these attributes;

3. Create a class object c of the class to which myuser belongs;c=myuser.getclass ();

4. Construct a for loop, the number of loops is the length of the list list;

4.1. Read the value of list [i], and then construct the set method corresponding to the property;

4.2, determine the type xxx of list [i], call getxxx (i) in the preparedstament statement, and then get the value of the field i;

4.3. Use the value obtained in 4.2 as the parameter of the set method obtained in 4.1.This completes the assignment of a field like a property,Just cycle like this;

See itThis is the credit of reflection,It's hard to imagine how difficult it would be to do the same thing without reflection! But reflection also has drawbacks,For example, the performance is relatively low and the security is more complicated.These are not discussed here,Interested readers can find answers online,There are many!

  • Previous Java observer pattern example
  • Next Star scoring function implemented by js