one. Java reflection mechanism
1. What is reflection: Reflection is to map various components in a Java class into Java objects one by one. For example: a class has: member variables, methods, construction methods, etc., packages and other information, using reflection technology can analyze a class, and map each component into an object.
2. Commonly used classes for Java reflection:
(1) Class class—can obtain class and class member information
(2) Field class—accessible class attributes
(3) Method—callable class methods
(4) Constructor—callable class
3. How to use reflection (basic steps):
(1) Import java.lang.reflect.* (
2) Obtain the Java.lang.Class object of the class that needs to be operated
(3) Call the method of Class to obtain Field, Method (
4) Use reflection API to operate (set properties, call methods)
4.Class class:
(1) Class class is the origin and entry of Java reflection mechanism
(2) The instantiated object of Class class represents a running Java Class or interface
· Each class has its own Class object
· Used to obtain various information related to the class
· Provides related methods to obtain class information
· Class class inherits from Object class
(3) Class class stores the structural information of the class
·Class name; ·Parent class, interface; ·Method, constructor, attribute; ·Note
5. Three ways to get Class object:
(1) Method 1:
//Method 1: object.getClass()
Student stu=new Student();
Class clazz=stu.getClass();
(2) Method 2:
//Method 2: Class.class
Class clazz= Student.class;
Class clazz=String.class;
Method 3:
// Method 3: Class.forName()
clazz=Class.forName("java.lang.String");
clazz=Class.forName("java.util.Date");
Example (code):
student information class (bean)
package org.reflect.Class;
public class Student {
private String name;
private int age;
private double score;
public Student() {
}
public Student(String name, int age, double score) {
this.name = name;
this.age = age;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
public void learn() {
System.out.println(this.name + "正在学习...");br/>}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", score=" + score
- "]";
}
}
Get the Class class object test class
package org.reflect.Class;
import java.lang.reflect.Modifier;
public class ClassDemo {
public static void main(String[] args) {
Student stu=new Student();
Class<?> c1=stu.getClass();//方式一
Class<Student> c2= Student.class;//方式二
Class<?> c3=null;
try {
c3=Class.forName("org.reflect.Class.Student"); // 方式三
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println("方式一获取的Class对象为:"+c1.getSimpleName());
System.out.println("方式二获取的Class对象为:"+c2);
System.out.println("方式三获取的Class对象为:"+c3);
int mod=c1.getModifiers();//获取修饰符所对应的整数
String modifier=Modifier.toString(mod);//获取修饰符
System.out.println(c1+"类所用的修饰符为:"+modifier);
}
}
Operation result:
Method 1 to obtain the Class object: Student
Method 2 to obtain the Class object: reflect.Student
Method 3 to obtain the Class object: reflect.Student
Modifier of the Student class: public
6. Use the Class class to obtain the class structure information
(1 ) to get the Class object of the class:
(2) Get the Filed object
(3) Get the Method object
(4) Get the Constructor object
Code example (the examples are based on the above Student class)
Example 1 (Get the Filed object)
package org.reflect.Filed;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
public class FiledDemo {
public static void main(String[] args) {
Class<Student> cl=Student.class;//获取代表Student类的Class对象
Field[] fields=cl.getDeclaredFields();//获取属性对象,返回数组
System.out.println(cl.getSimpleName()+"类中声明的属性有:");
for(Field f:fields){
String filedName=f.getName();//获取属性名
Class<?> filedType=f.getType();//获取属性类型
int mod=f.getModifiers();//获取修饰符对应整数
String modifier=Modifier.toString(mod);//获取修饰符
System.out.println(modifier+" "+filedType.getSimpleName()+" "+filedName);
}
}
}
Running result:
The properties declared in the Student class are:
private String name
private int age
private double score
Example 2 (obtaining the Method object)
package method;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class MethodDemo {
public static void main(String[] args) {
try {
Class<?> cls=Class.forName("method.Student");
Method[] methods=cls.getDeclaredMethods();
for(Method method:methods){
String methodName=method.getName(); // 获取方法名称
Class<?> returnType=method.getReturnType(); // 获取方法的返回值类型
String modStr=Modifier.toString(method.getModifiers()); // 获取方法的修饰符
Class<?>[] paramTypes=method.getParameterTypes(); // 获取参数类型
System.out.print(modStr+" "+returnType.getSimpleName()+" "+methodName+"(");
if(paramTypes.length==0){
System.out.print(")");
}
for(int i=0;i<paramTypes.length;i++){ // 遍历形式参数类型
if(i==paramTypes.length-1){
System.out.print(paramTypes[i].getSimpleName()+" args"+i+")");
}else{
System.out.print(paramTypes[i].getSimpleName()+" args"+i+",");
}
}
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
运行结果:
public void eat(String args0,String args1)
public int getAge()
public void setAge(int args0)
public double getScore()
public void setScore(double args0)
7. Use reflection to dynamically create objects
(1) Method 1:
Use the newInstance() method of Class, which is only applicable to the no-argument constructor
(2) Method 2:
Method 2: Call the newInstance() method of the Constructor, which applies to all construction methods
Example 3 (getting the Constructor object)
package org.reflect.Constructor;
import java.lang.reflect.Constructor;
public class ConstructorDemo {
public static void main(String[] args) {
Class<Student> cl=Student.class;//获取Class对象,代表Student类
try {
Constructor<Student> con=cl.getDeclaredConstructor(String.class,int.class,double.class);//获取散参构造方法
Student stu=con.newInstance("张无忌",23,96.7);
System.out.println(stu);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Running result:
Student [name=Zhang Wuji, age=23, score=96.7]
Example 4 (dynamic creation method):
package method;
import java.lang.reflect.Method;
public class InvokeMethod {
public static void main(String[] args) {
Class<Student> cls=Student.class;
try {
Student stu=cls.newInstance(); // 通过反射机制实例化对象,使用此newInstance()方法,要求类中必须包含一个无参构造方法
Method setNameMethod=cls.getMethod("setName",String.class);
setNameMethod.invoke(stu,"风清扬"); // 使用stu对象调用setName(String name)方法,传入"风清扬"参数
Method getNameMethod=cls.getMethod("getName");
System.out.println(getNameMethod.invoke(stu)); // 使用stu对象调用getName()方法,返回一个值
} catch (Exception e) {
e.printStackTrace();
}
}
}
Running result:
Breeze