Home > Back-end >  Java reflection (preliminary)
Java reflection (preliminary)

Time:10-20

Reflection (Reflection) is the key to be regarded as a dynamic language, Reflection mechanism allows the program execution with the help of the Reflection API to achieve any kind of internal information, and can directly manipulate arbitrary objects of internal attributes and methods,
After loading the Class, in the method of heap memory area creates a Class object of type (a Class has only one Class object), this object contains the full Class structure information, we can see through this object Class structure, the object is like a mirror, see the structure of the Class through the mirror, so, our image is called: reflection,
,

Java reflection mechanism provides the function of the
any judgment in running a
object belonging to the classConstructed at run time any of a class object
At run time to judge any one class member variables and methods are
At run time for generic information
At runtime to invoke any member variables and methods of the object
At runtime processing annotation
Generate dynamic proxy

 
Public class ClassTest {
@ Test
Public void test1 () throws the Exception {
//create a Class Class object
The Class clazz=Person. The Class;
//create the Person class objects through reflection
Constructor con=clazz. GetConstructor (String class, int. J class);
The Object obj=con. NewInstance (" Bob ", 12);
System. The out. Println (obj);

//call the method that the Person class, attribute
Field age=clazz. GetDeclaredField (" age ");
Age. The set (obj, 20);
System. The out. Println (obj);
Method the show=clazz. GetDeclaredMethod (" show ");
Show. Invoke (obj);
}
}

The class Person {
private String name;
public int age;
Public Person (String name, int age) {
this.age=age;
this.name=name;
}
Public void show () {
System. The out. Println (" I am show method ");
}
@ Override
Public String toString () {
Return "Person {name=" + name + ", the age="+ age +"} ";
}
}

CodePudding user response:

This example does speak very deeply

CodePudding user response:

Reflection speak it well

CodePudding user response:

  • Related