Java Basics 26~Reflection

Like you who love programming!
Learn SpringBoot actual combat course https://edu.csdn.net/course/detail/31433
Learn SpringCloud introductory course https://edu.csdn.net/course/detail/31451


Preface

Reflection is an important skill of Java. After mastering reflection, it is helpful to master the underlying principles of various Java frameworks.

What is reflection mechanism

Reflection is to dynamically obtain class methods, properties, construction methods and other internal member information when the program is running, dynamically create class objects, and call class properties and methods.

What can reflection do

Greatly improve the flexibility of the program, so that you can write very versatile code.
The mainstream enterprise-level frameworks all use reflection mechanisms: Spring, Hibernate, MyBatis, Shiro, etc.

Pros and cons of reflection

Advantages: flexibility and versatility
Disadvantages: reduced code readability, program performance

Reflected API

java.lang.reflect 包

  • Class type
  • Method class method
  • Field class attributes
  • Constructor class construction method

reflection

The process of using reflection

  1. Obtain the Class object
  2. Obtain the methods and attributes of the class through the Class object
  3. Create objects through reflection
  4. Call methods and properties through objects

Several ways to obtain Class

  1. Class name.class obtained by class
  2. Object.getClass() Obtained by object
  3. Class.forName("package name + class name") dynamically loads the class into memory

Obtain class attribute and method information at runtime

Class method:

  • Method[] getDeclaredMethods() get all declared methods
  • Field[] getDeclaredFields() to get all declared properties

Method method:

  • String getName() Get the method name
  • Class getReturnType() Get the return value type
  • int getModifiers() to obtain access modifiers
  • Class[] getParameterTypes() get all parameter types

Field method:

  • String getName() Get the method name
  • Class getType() get the type
  • int getModifiers() to obtain access modifiers

Create objects, call methods and properties

Class method:

  • Object newInstance() To create an object, a construction method without parameters must be provided
  • Method getMethod(String name,Class... paramType) to obtain a specific method
    name is the method name, paramType is the type of the parameter

Methods of the Method class:

  • Object invoke(Object obj,Object... params)
    obj is the object that calls the method, and params is the value of the parameter

Call the specified constructor

Class method:

  • Constructor getContructor(Class... paramType) to obtain the constructor
    paramType is the parameter type of the constructor

Constructor method:

  • Object newInstance(Object… params) Create object
    params is the value of the parameter

Reflection case

Case: Obtain the attribute and method information of the class at runtime

class Person{
	private String name;
	private Integer age;
	public Person(){
		
	}
	public Person(String name,Integer age){
		this.name = name;
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public void sayHi(){
		System.out.println("Hi:"+name+","+age);
	}
}
public class ReflectTest {

	public static void main(String[] args){
		try {
			//获得类型
			Class clazz = Person.class;
			//获得所有的属性
			Field[] fields = clazz.getDeclaredFields();
			for(Field f : fields){
				//属性名称
				String name = f.getName();
				//属性类型
				Class c = f.getType();
				System.out.println(name+" - "+c);
			}
			//获得所有的方法
			Method[] methods = clazz.getDeclaredMethods();
			for(Method m : methods){
				//方法名
				String name = m.getName();
				//返回值类型
				Class returnType = m.getReturnType();
				System.out.print(returnType + " " + name + "(");
				//参数
				Class[] params = m.getParameterTypes();
				for(Class c : params){
					System.out.print(" " + c.getName());
				}
				System.out.println(")");
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}

Case: create object, call method

try {
	//获得类型
	Class clazz = Person.class;
	//获得类的对象,调用默认的构造方法
	Object obj = clazz.newInstance();
	//获得对象的方法
	Method m1 = clazz.getMethod("setName", String.class);
	Method m2 = clazz.getMethod("setAge", Integer.class);
	Method m3 = clazz.getMethod("sayHi");
	//调用方法
	m1.invoke(obj, "micheal");
	m2.invoke(obj, 20);
	m3.invoke(obj);
} catch (Exception e) {
	e.printStackTrace();
} 

Case: call the specified construction method

try {
	//运行时将Person类加载到内存中
	Class clazz = Person.class;
	//获得指定的构造方法
	Constructor con = clazz.getConstructor(String.class,Integer.class);
	//调用构造方法
	Object obj = con.newInstance("Jim",30);
	//调用方法
	Method m = clazz.getMethod("sayHi");
	m.invoke(obj);
} catch (Exception e) {
	e.printStackTrace();
} 

Case: Use reflection to complete JSON parsing

public class JSONUtils{
   /**
    * 解析JSON,返回Java对象
    * @param json JSON字符串
    * @param clazz Java类型
    * @return Java对象
    * @throws Exception
    */
    public static Object fromJSON(String json,Class clazz) throws Exception {
        Object obj = clazz.newInstance();
        //去掉JSON字符串前后{}和"
        json = json.replace("{", "").replace("}", "").replace("\"","");
        //按,分割字符串
        String[] strings = json.split("\\,");
        for(String str : strings){
            //再按:分割出属性名和属性值
            String[] strs = str.split("\\:");
            String name = strs[0];
            String value = strs[1];
            //获得属性
            Field field = clazz.getDeclaredField(name);
            //修改属性为可以访问,因为是private的
            field.setAccessible(true);
            Object val = null;
            //判断属性类型,转换值的类型
            if(field.getType() == Integer.class){
                val = Integer.valueOf(value);
            }else{
                val = value;
            }
            //属性赋值
            field.set(obj,val);
        }
        //返回对象
        return obj;
    }

	public static void main(String[] args) throws Exception {
        String json = "{\"name\":\"张三\",\"age\":\"20\"}";
        Person person = (Person) JSONUtils.fromJSON(json,Person.class);
        person.sayHi();
    }
}

End

Assignment: Use reflection to convert Java objects to JSON


If you need to learn other Java knowledge, poke here ultra-detailed knowledge of Java Summary

Guess you like

Origin blog.csdn.net/u013343114/article/details/112980085