First, Introduction
Java reflection is a mechanism that allows us to get internal information about classes such as methods, properties, parent classes, interfaces, and so on at run time. In other words, reflection is essentially a "reverse-coming" process. When we new
create an instance of a class, is actually built by the Java Virtual machine at runtime based on the object of this class Class
, and reflection is the object of a class Class
to obtain its definition information, so that we can access its properties, methods, know the class of the parent class, Information such as which interfaces are implemented.
Second, class category
We know that using Javac can compile. java files into. class files, which contain our original definition information (parent class, interface, constructor, property, method, etc.) for the class. The. class file is ClassLoader
run Loaded into the Java Virtual Machine (JVM), when a. class file is loaded, the JVM generates a class object for it, and the object we instantiate in the program is actually constructed from the corresponding class object at runtime. Specifically, this class object is actually java.lang.Class<T>
an instance of a generic class, such as Class<MyClass>
an instance of an object that encapsulates the MyClass
definition information for a class Class<T>
. Since java.lang.Class<T>
the class does not have a public constructor, we cannot instantiate the class directly, and we can get a class object in the following ways.
In the following tutorial, we will take the people class and the student class for example:
public class People {
private String name;
private int age;
Public people (String name, int age) {
this.name = name;
This.age = age;
}
public int getage () {return age
;
}
Public String GetName () {return
name;
}
public void Setage (int age) {
this.age = age;
}
public void SetName (String name) {
this.name = name;
}
public void Speak () {
System.out.println (getName () + "" + getage ());
}
Public class Student extends people {
private int grade;
Public Student (String name, int age) {
super (name, age);
}
Public Student (String name, int age, int grade) {
super (name, age);
This.grade = grade;
}
public int Getgrade () {return
grade;
}
public void Setgrade (int grade) {
this.grade = grade;
}
private void Learn (String course) {
System.out.println (name + "Learn" + course);
}
To get a class object from a class name
If you know the name of a class at compile time, we can get its class object like this:
class<people> peopleclass = People.class;
There is also a way to get the class object based on the full pathname of the class as follows:
Suppose the People class is
class<people> Peopleclass = Class.forName ("Com.test.People") in the Com.test package;
Note that the Class.forName()
parameter of the method must be a full path name of a class. In fact, as long as we "import com.test.People", we can directly through " People.class
" to get his class object, without writing a full path so troublesome. (If the Class.forName()
corresponding class is not found when the method is invoked, classpath
it is thrown ClassNotFoundException
.) )
Get its class object from the object itself
People people = New People ("Bill");
class<people> Peopleclass = People.getclass ();
Getting constructors for classes by reflection
Once we have People
the class object, we can get the original definition information of the class from this class object People
. First, we get the People
constructor object of the class, and with this constructor object we can construct an People
object. For example, we can add the following code to the Student.java:
public static void Main (string[] args) {
class<people> pclass = people.class;
try {
constructor<people> constructor = Pclass.getconstructor (String.class, int.class);
People people = constructor.newinstance ("Bill");
Obj.speak ();
} catch (Exception e) {
}
}
In the above, we call the getConstructor
method to get the People
constructor object of a class, because we want to get the parameter type of the String
constructor int
, and so we pass in the String.class
and int.class
. With the constructor object, we can invoke the newInstance
method to create an people
object.
Note that when you get to the object of a class by reflection, Constructor
Method
Field
accessible
You can raise the reflection speed by setting the flag of this object to cancel the true
Java language access check before calling the methods of the objects. As shown in the following code:
Constructor<people> constructor = Peopleclass.getconstructor (String.class,
int.class);
Set the accessible property for constructor to Ture to cancel the Java access check
constructor.setaccessible (true);
Retrieving methods declared in a class by reflection
Gets the method declared in the current class (excluding inherited from the parent class)
To get all the methods declared in the current class can pass through a getDeclaredMethods
function in class, it gets to all the methods declared in the current classes (including private
, public
,, and static
so on), it returns an Method
array of objects, where each Method
Object represents a method declared in a class. To get the specified method, you can call the getDeclaredMethod(String name, Class...<T> parameterTypes)
.
As shown in the following code:
private static void Showdeclaredmethods () {
Student Student = new Student ("Bill");
Gets all the methods declared by the student class
method[] methods = Student.getclass (). Getdeclaredmethods ();
try {
//Get Learnmethod Object (encapsulated Learn method) methods
Learnmethod = Student.getclass (). Getdeclaredmethod ("Learn",
string.class);
Gets the parameter list of the Learn method and prints it out
class<?>[] paramclasses = Learnmethod.getparametertypes ();
for (class<?> class:paramclasses) {
System.out.println ("Parameters of Learn Method:" + class.getname ());
}
Determine if the Learn method is private
System.out.println (learnmethod.getname () + ' is private '
+ modifier.isprivate ( Learnmethod.getmodifiers ()));
Call Learn method
Learnmethod.invoke (student, "Java Reflection");
} catch (Exception e) {
}
}
Gets the public method declared in the current class and the parent class
To get the current class and all the methods declared in the parent class public
can call the getMethods
function, and to get a specified public
method, you can call the getMethod
method. Please see the following code:
private static void Showmethods () {
Student Student = new Student ("Mr.simple");
Gets all public methods, including the student itself and inherited from the parent class
method[] methods = Student.getclass (). GetMethods ();
try {
//Note that only public methods can be obtained through GetMethod, and an exception method
Learnmethod = Student.getclass () is thrown if an attempt to get the private methods is attempted. GetMethod ("Learn", String.class);
} catch (Exception e) {
}
}
Getting the properties defined in a class by reflection
Getting the property is similar to getting the method, except that getMethods()
the getDeclaredMethods()
call to/method is replaced with a getFields()
call to/ getDeclaredFields()
method.
Gets the properties defined in the current class (excluding properties inherited from the parent class)
To get all the properties defined in the current class (including private
, public
,, and static
so on) can call the function of the class object, and to getDeclaredFields
get the specified property, you can call the getDeclaredField
.
As shown in the following code:
private static void Showdeclaredfields () {
Student Student = new Student ("Bill");
Gets all the properties defined in the current class
field[] fields = Student.getclass (). Getdeclaredfields ();
try {
//Get the specified property
Field Gradefield = Student.getclass (). Getdeclaredfield ("grade");
Gets the property value
System.out.println ("The Grade is:" + gradefield.getint (student));
Sets the property value
gradefield.set (student);
} catch (Exception e) {
}
}
Gets the public property defined in the current class and the parent class
To get all the properties defined in the current class and the parent class public
can call Class
the object's getFields
function, and to get a specified public
property, you can call the getField
method, as shown in the following code:
private static void Showfields () {
Student Student = new Student ("Bill");
Gets all public properties of the current class and the parent class
field[] Publicfields = Student.getclass (). GetFields ();
}
Get the parent class of the class and the interface implemented by the class by reflection
Get parent class
Class
you can invoke the method of the object getSuperClass
, as shown in the following code:
Student Student = new Student ("Bill");
Class<?> superclass = Student.getclass (). Getsuperclass ();
To get the implemented interface
To know which interfaces a class implements, simply call Class
the object's getInterfaces
method, as shown in the following code:
private static void Showinterfaces () {
Student Student = new Student ("Bill");
Class<?>[] interfaces = Student.getclass (). Getinterfaces ();
}
Summarize
The above is the entire content of this article, I hope for everyone's study and work can help.