JavaSE reflection-using reflection to call methods

One, use reflection to call methods

  • Four key
    objects
    Method name
    Actual parameter list
    Return value
public class User {
    
    

	public int id;
	
	private String name;
	
	String address;
	
	protected int sno;
	
	public User() {
    
    }
	
	public User(int id, String name, String address, int sno) {
    
    
		super();
		this.id = id;
		this.name = name;
		this.address = address;
		this.sno = sno;
	}
	
	public void study() {
    
    
		System.out.println("study...");
	}
	
	public void eat(int a,String b) {
    
    
		System.out.println("eat...");
	}

	@Override
	public String toString() {
    
    
		return "User [id=" + id + ", name=" + name + ", address=" + address + ", sno=" + sno + "]";
	}

	@Override
	public int hashCode() {
    
    
		final int prime = 31;
		int result = 1;
		result = prime * result + ((address == null) ? 0 : address.hashCode());
		result = prime * result + id;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		result = prime * result + sno;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
    
    
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		User other = (User) obj;
		if (address == null) {
    
    
			if (other.address != null)
				return false;
		} else if (!address.equals(other.address))
			return false;
		if (id != other.id)
			return false;
		if (name == null) {
    
    
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		if (sno != other.sno)
			return false;
		return true;
	}
}
import java.lang.reflect.Method;

public class Test {
    
    
	public static void main(String[] args) throws Exception {
    
    
		Class usrClass = Class.forName("com.lzj.reflect.pojo.User");
        // 创建对象
        Object obj = usrClass.newInstance();
        // 获取方法
        Method eatMethod = usrClass.getDeclaredMethod("eat", int.class, String.class); // "方法名",参数类型,参数类型
        // 调用方法(使用invoke)并返回值
        Object retValue = eatMethod.invoke(obj, 3,"lzj");
        System.out.println(retValue);
	}
}

Two, invoke()

@CallerSensitive
public Object invoke(Object obj, Object... args)
    throws IllegalAccessException, IllegalArgumentException,
       InvocationTargetException
{
    
    
    if (!override) {
    
    
        if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
    
    
            Class<?> caller = Reflection.getCallerClass();
            checkAccess(caller, clazz, obj, modifiers);
        }
    }
    MethodAccessor ma = methodAccessor;             // read volatile
    if (ma == null) {
    
    
        ma = acquireMethodAccessor();
    }
    return ma.invoke(obj, args);
}
  • The first parameter is the object to which the method belongs (if it is a static method, you can pass null directly)
  • The second variable parameter is the parameter of the method
  • Method.invoke() itself uses an array to wrap the parameters; and each call must check the visibility of the method (in Method.invoke()), and also check the type matching of each actual parameter and the formal parameter (in NativeMethodAccessorImpl .invoke0() or the generated Java version MethodAccessor.invoke())

1. Implementation Principle

  • Invoke() is not actually the reflection call logic implemented by itself, but is delegated to sun.reflect.MethodAccessor for processing. Each actual Java method has only one corresponding Method object as the root, and this root will not be exposed to the user , But every time a Method object is obtained through reflection, a new Method object is created to wrap the root and then given to the user. Before the invoke() method of the Method object corresponding to an actual Java method is called for the first time, the MethodAccessor of the calling logic is implemented. The object has not been created yet, wait for the first call to create a new MethodAccessor and update it to root, and then call MethodAccessor.invoke() to actually complete the reflection call

Guess you like

Origin blog.csdn.net/LvJzzZ/article/details/108980429