This article brings you what is the Java reflection mechanism? The method of using Java reflection mechanism has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Speaking of the reflection mechanism, people who come into contact with it for the first time may be confused. Reflection? What reflection? How to reflect? What is reflection for? Next, I will talk about Java's reflection machine in this article
But before that, there is still a problem that needs to be solved. The dynamics in the title name. Speaking of dynamics, Let me first introduce dynamic language and static language
##static language
Static language is Languages in which the data type of the variable can be determined at compile time. Most statically typed languages require that the data type must be declared before using the variable. For example: C, Java, Delphi, C#, etc.
Dynamic language
Dynamic language is a language that determines the data type at runtime. There is no need for a type declaration before a variable is used. Usually the type of the variable is the type of the value to which it is assigned. For example, PHP/ASP/Ruby/Python/Perl/ABAP/SQL/JavaScript/Unix Shell, etc. andDynamic language means that the program can change its structure while it is running: new functions can be introduced, existing functions can be deleted and other structural changes.
At this time, you may have questions. Since Java is a static language, how can it be dynamic? One is that Java has a mechanism related to dynamics: Reflection mechanism. Through the reflection mechanism, Java can load, detect and use classes that are completely unknown during compilation when the program is running, and can generate related class object instances, so that its methods can be called or a certain attribute value can be changed. So JAVA can also be regarded as a semi-dynamic language
Let’s talk about the reflection mechanism
Reflection mechanism concept The reflection mechanism in Java means that in the running state, any class can know all the properties and methods of this class; And for any object, any of its methods can be called; this function of dynamically obtaining information and dynamically calling object methods is called the reflection mechanism of the Java language.
The principle of reflection lies in the Class object
Take a look at the process of program loading
You can probably see from the picture what reflection is used for, then let’s talk about other aspects of reflection
Reflection API
The reflection API is used to generate information about classes, interfaces or objects in the JVM. -
Class: The core class of reflection, which can obtain the attributes, methods and other information of the class. -
Field class: A class in the Java.lang.reflec package, which represents the member variables of the class and can be used to get and set attribute values in the class. -
Method class: The class in the Java.lang.reflec package represents the method of the class. It can be used to obtain method information or execute methods in the class. -
Constructor class: Class in the Java.lang.reflec package, representing the construction method of the class.
Let’s talk about how to use reflection
1. Steps
2. Method to obtain Class object
//假设我们有一个Student类 方法一、(推荐) Class clas = Class.forName("first.Student");//“”里写的是类的全路径 方法二、 Student stu = new Student(); Class clas = stu.getClass(); 方法三、 Class clas = Student.Class;
3. Get the constructor method, Field, main method and call
Student.java
public class Student { public String name; protected int age; char sex; private String phoneNum; public static void main(String[] args) { System.out.println("main方法执行了。。。"); } //---------------构造方法------------------- Student(String str) { System.out.println("(默认)的构造方法 s = " + str); } // 无参构造方法 public Student() { System.out.println("调用了公有、无参构造方法执行了。。。"); } // 有一个参数的构造方法 public Student(char name) { System.out.println("姓名:" + name); } // 有多个参数的构造方法 public Student(String name, int age) { this.name=name;this.age=age; System.out.println("姓名:" + name + "年龄:" + age);// 这的执行效率有问题,以后解决。 } // 受保护的构造方法 protected Student(boolean n) { System.out.println("受保护的构造方法 n = " + n); } // 私有构造方法 private Student(int age) { System.out.println("私有的构造方法 年龄:" + age); } public String toString() { return "Student [name=" + name + ", age=" + age + ", sex=" + sex + ", phoneNum=" + phoneNum + "]"; } }
Constructors.java(构造方法)
package first; import java.lang.reflect.Constructor; public class Constructors { public static void main(String[] args) throws Exception { Class clas=Class.forName("first.Student"); System.out.println("所有公有构造方法"); Constructor[] conArry=clas.getConstructors(); for(int i=0;i<conArry.length;i++) { System.out.println(conArry[i]); } System.out.println("所有的构造方法"); conArry=clas.getDeclaredConstructors(); for(int i=0;i<conArry.length;i++) { System.out.println(conArry[i]); } System.out.println("获取公有无参的构造方法"); Constructor con=clas.getConstructor(null); System.out.println("con="+con); Object obj=con.newInstance(); System.out.println("获取私有构造方法,并调用"); con=clas.getDeclaredConstructor(char.class); System.out.println(con); //con.setAccessible(true);//暴力访问,针对private方法和字段时使用 obj=con.newInstance('a');//创建对象 } }
输出
所有公有构造方法 public first.Student(char) public first.Student() public first.Student(java.lang.String,int) 所有的构造方法 protected first.Student(boolean) private first.Student(int) public first.Student(char) public first.Student() first.Student(java.lang.String) public first.Student(java.lang.String,int) 获取公有无参的构造方法 con=public first.Student() 调用了公有、无参构造方法执行了。。。 获取私有构造方法,并调用 public first.Student(char) 姓名:a
Fields.java(字段)
package first; import java.lang.reflect.Field; public class Fields { public static void main(String[] args)throws Exception { // TODO Auto-generated method stub Class StuClass=Class.forName("first.Student"); System.out.println("获取所有公有的字段"); Field[] fieldArry=StuClass.getFields(); for(Field f:fieldArry) { System.out.println(f); } System.out.println("获取所有的字段(包括私有、受保护、默认的)"); fieldArry=StuClass.getDeclaredFields(); for(Field f:fieldArry) { System.out.println(f); } System.out.println("获取公有字段并调用"); Field f = StuClass.getField("name"); System.out.println(f); Object obj=StuClass.getConstructor().newInstance(); StuClass.getConstructor(String.class,int.class).newInstance("a",10); f.set(obj, "b"); Student stu=(Student)obj; System.out.println(stu.name); System.out.println("获取私有字段并调用"); f = StuClass.getDeclaredField("phoneNum"); System.out.println(f); f.setAccessible(true);//暴力反射,解除私有限定 f.set(obj, "18888889999"); System.out.println("验证电话:" + stu); } }
输出
获取所有公有的字段 public java.lang.String first.Student.name 获取所有的字段(包括私有、受保护、默认的) public java.lang.String first.Student.name protected int first.Student.age char first.Student.sex private java.lang.String first.Student.phoneNum 获取公有字段并调用 public java.lang.String first.Student.name 调用了公有、无参构造方法执行了。。。 姓名:a年龄:10 b 获取私有字段并调用 private java.lang.String first.Student.phoneNum 验证电话:Student [name=b, age=0, sex=
Main.java
package first; import java.lang.reflect.Method; public class Main { public static void main(String[] args) { try { // 1、获取Student对象的字节码 Class clazz = Class.forName("first.Student"); // 2、获取main方法 Method methodMain = clazz.getMethod("main", String[].class);// 第一个参数:方法名称,第二个参数:方法形参的类型, // 3、调用main方法 // methodMain.invoke(null, new String[]{"a","b","c"}); // 第一个参数,对象类型,因为方法是static静态的,所以为null可以,第二个参数是String数组 // 这里拆的时候将 new String[]{"a","b","c"} 拆成3个对象。。。所以需要将它强转。 methodMain.invoke(null, (Object) new String[] {});// 方式一 // methodMain.invoke(null, new Object[]{new String[]{"a","b","c"}});//方式二 } catch (Exception e) { e.printStackTrace(); } } }
The above is the detailed content of What is Java reflection mechanism? How to use Java reflection mechanism. For more information, please follow other related articles on the PHP Chinese website!