博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java反射----根据方法名,类和对象执行对象的该方法
阅读量:4672 次
发布时间:2019-06-09

本文共 838 字,大约阅读时间需要 2 分钟。

按例子讲,比较易懂。

例子:一个Test类,Test类中有run方法,通过字符串“run”执行该类的对象的run方法。

java代码:

1.类

public class Test {	public void run(String a){		System.out.println(a+"反射的测试方法");	}}
2.实现方法

public static void main(String[] args) {		String methodName="run";		Class formatter=Test.class;		Test t1=new Test();		Method cMethod;		try {			cMethod = formatter.getMethod(methodName, new Class[]{String.class});			String aa=(String) cMethod.invoke(t1, new Object[]{"罗成"});		}		catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {			e.printStackTrace();		}  		catch (NoSuchMethodException e) {			e.printStackTrace();		} 		catch (SecurityException e) {			e.printStackTrace();		}	}

其中,

1.Method cMethod = formatter.getMethod(方法名, 参数的类型类数组);

2.cMethod.invoke(执行方法的对象, 参数数组);

其中2的放回值是object

转载于:https://www.cnblogs.com/marx-luo/p/6713089.html

你可能感兴趣的文章