java 反射 调用无参数方法?
2个回答
2015-07-10 · 知道合伙人互联网行家
关注
展开全部
通过Java反射调用无参数方法,这是个测试用的例子,通过反射调用对象的方法,代码如下:
import java.lang.reflect.Method;
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信息!
Process finished with exit code 0
展开全部
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class MethodInvokation {
public static void main(String[] args) throws NoSuchMethodException,
SecurityException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
Test test = new Test();
Class<?> clazz = test.getClass();
Method method = clazz.getMethod("test");
System.out.println(method.invoke(test));
}
}
class Test {
public Object test() {
return null;
}
}
import java.lang.reflect.Method;
public class MethodInvokation {
public static void main(String[] args) throws NoSuchMethodException,
SecurityException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
Test test = new Test();
Class<?> clazz = test.getClass();
Method method = clazz.getMethod("test");
System.out.println(method.invoke(test));
}
}
class Test {
public Object test() {
return null;
}
}
追问
奇怪昨天的代码今天又好使了。
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询