Java reflection-access to member methods

reflection

Through the Java reflection mechanism, the description of the Java object that has been loaded into the JVM can be accessed in the program, and the function of accessing, detecting and modifying the information describing the Java object itself can be realized. Through reflection, you can access constructors, member variables, and member methods.

Access to the constructor: Java reflection-access to the constructor
access to member variables: Java reflection-access to member variables

Access member method

Use the Method object to manipulate the corresponding method.
Insert picture description here
Common methods provided by the Method class

method Description
getName() Get the name of the method
getParameterTypes() Obtain the type of each parameter of the method in the form of a Class array in the order of declaration
getReturnType () Obtain the return value type of the method in the form of a Class object
getExceptionTypes() Get the type of exception that the method may throw in the form of a Class array
invoke(Object obj, Object … args) Use the specified parameter args to execute the method in the specified object obj, and the return value is Object type
isVarArgs() Check whether the constructor is allowed to have a variable number of parameters, if it is allowed to return true, it is not allowed to return false
getModifiers() Get an integer that can be parsed out of the modifier used by the method

The return value of the getModifiers() method is the modifier information represented. A series of static methods for parsing are provided in this class. You can not only check whether it is modified by the specified modifier, but also get all of them in the form of a string Modifier.
Common analytical methods in the Modifier class:

Static method Description
isPublic(int mod) Check whether it is modified by the public modifier, if it is true, otherwise it returns false
isProtected(int mod) Check whether it is modified by the protected modifier, if it is true, otherwise it returns false
isPrivate(int mod) Check whether it is modified by the private modifier, if it is true, otherwise it returns false
isStatic(int mod) Check whether it is modified by the static modifier, if it is true, otherwise it returns false
isFinal (int mod) Check whether it is modified by the Final modifier, if it is true, otherwise it returns false
toString(int mod) Return all modifiers as a string

Write an example to reflect how many methods there are in a class, take java.lang.String as an example.

public class Study2 {
    
    

	public static void main(String[] args) {
    
    
		try {
    
    
			Class c = Class.forName("java.lang.String");// 创建class对象
			Method ms[] = c.getDeclaredMethods();// 获得所有的方法
			for (Method m : ms) {
    
    
				System.out.print(Modifier.toString(m.getModifiers()) + " ");// 获取所有方法的修饰符
				System.out.print(m.getReturnType().getSimpleName() + " ");// 获取方法的返回值类型
				System.out.print(m.getName() + "(");// 获取方法的名字
				Class cla1[] = m.getParameterTypes();// 获取方法的参数类型
				for (int i = 0; i < cla1.length; i++) {
    
    
					System.out.print(cla1[i].getSimpleName() + " args ");
				}
				System.out.print(")");
				Class cla2[] = m.getExceptionTypes();// 获取方法可能抛出的异常
				for (int i = 0; i < cla2.length; i++) {
    
    
					System.out.print(cla2[i].getSimpleName());
				}
				System.out.println(" {   }");
			}
		} catch (ClassNotFoundException e) {
    
    
			e.printStackTrace();
		}

	}
}

Insert picture description here
The modifiers, method names, return value types, method parameters, and exceptions that may be thrown by the methods are output.

Knowing how to reflect these methods, how to call these methods? Create a simple member method in Study.

public class Study {
    
    
	public void add(int a, int b) {
    
    
		System.out.println("a+b="+(a+b));
	}

}

Calculate the value of a+b. Called in Study2, calculated.

public class Study2 {
    
    

	public static void main(String[] args) {
    
    
		try {
    
    
			Class c = Class.forName("study.czm.Study");// 创建class对象
			Method ms[] = c.getDeclaredMethods();// 获得所有的方法
			for (Method m : ms) {
    
    
				System.out.print(Modifier.toString(m.getModifiers()) + " ");// 获取所有方法的修饰符
				System.out.print(m.getReturnType().getSimpleName() + " ");// 获取方法的返回值类型
				System.out.print(m.getName() + "(");// 获取方法的名字
				Class cla1[] = m.getParameterTypes();// 获取方法的参数类型
				for (int i = 0; i < cla1.length; i++) {
    
    
					System.out.print(cla1[i].getSimpleName() + " args ");
				}
				System.out.print(")");
				Class cla2[] = m.getExceptionTypes();// 获取方法可能抛出的异常
				for (int i = 0; i < cla2.length; i++) {
    
    
					System.out.print(cla2[i].getSimpleName());
				}
				System.out.println(" {   }");
			}

			Constructor cs = c.getConstructor();// 创建实例化对象
			Object obj = cs.newInstance();// 无参构造方法创建对象
			Method m = c.getDeclaredMethod("add", int.class, int.class);// 创建方法对象
			m.invoke(obj, 1, 2);

		} catch (ClassNotFoundException e) {
    
    
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
    
    
			e.printStackTrace();
		} catch (SecurityException e) {
    
    
			e.printStackTrace();
		} catch (InstantiationException e) {
    
    
			e.printStackTrace();
		} catch (IllegalAccessException e) {
    
    
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
    
    
			e.printStackTrace();
		} catch (InvocationTargetException e) {
    
    
			e.printStackTrace();
		}

	}
}

Insert picture description here

Guess you like

Origin blog.csdn.net/javanofa/article/details/104841638