java中由类名和方法名字符串实现其调用【反射机制】
import java.lang.reflect.Method;
public class Test {
public static void main(String[] args) throws Exception {
String className = "com.runqianapp.ngr.alias.example.FunClass";
String methodName = "sayHello";
Class clz = Class.forName(className);
//
Object obj = clz.newInstance();
//获取方法
Method m = obj.getClass().getDeclaredMethod(methodName, String.class);
//调用方法
String result = (String) m.invoke(obj, "aaaaa");
System.out.println(result);
}
}
class FunClass{
public String sayHello(String s){
System.out.println(s);
return "hello!";
}
}
2.
import java.lang.reflect.InvocationTargetException;
/**
* Created by IntelliJ IDEA.
* File: TestRef.java
* User: Administrator
* Date: 2015-7-10 16:28:44
*/
public class TestRef {
public static void main(String args[]) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
Foo foo = new Foo("这个一个Foo对象!");
Class clazz = foo.getClass();
Method m1 = clazz.getDeclaredMethod("outInfo");
Method m2 = clazz.getDeclaredMethod("setMsg", String.class);
Method m3 = clazz.getDeclaredMethod("getMsg");
m1.invoke(foo);
m2.invoke(foo, "重新设置msg信息!");
String msg = (String) m3.invoke(foo);
System.out.println(msg);
}
}
class Foo {
private String msg;
public Foo(String msg) {
this.msg = msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getMsg() {
return msg;
}
public void outInfo() {
System.out.println("这是测试Java反射调用无参数方法的测试类");
}
}
控制台输出结果:这是测试Java反射调用无参数方法的测试类
重新设置msg信息!
————————————————
版权声明:本文为CSDN博主「weixin_39612038」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_39612038/article/details/114132873