我有下面的类,当我调用myClass.doprocess()时,我应该得到字符串“hai”,我该如何实现呢?
public class myClass{
public int doprocess(){
dataClass objSt = new dataClass();
Class newCls = objSt.getClass();
Method[] methods = newCls.getMethods();
for (Method method : methods) {
if(method.getName() == "getList"){
return method;
}
}
}
}
class dataClass{
public String getList(){
return "hai,";
}
}
如果我执行上面的代码,我会得到响应
public java.lang.String com.myproject.controller.dataClass.getList()
但我需要将响应作为getList函数的返回值
答案 0 :(得分:1)
您可以使用getDeclaredMethod获取具有给定名称和参数集的方法,然后您可以使用Method.invoke(instance, params...)来调用该方法。
class myClass {
public String doprocess() throws SecurityException, NoSuchMethodException,
IllegalArgumentException, IllegalAccessException,
InvocationTargetException {
dataClass objSt = new dataClass();
Method m = dataClass.class
.getDeclaredMethod("getList", (Class<?>) null);
return (String) m.invoke(objSt, (Object) null);
}
}
class dataClass {
public String getList() {
return "hai,";
}
}
测试
public class Test {
public static void main(String[] args) throws SecurityException,
IllegalArgumentException, NoSuchMethodException,
IllegalAccessException, InvocationTargetException {
myClass m = new myClass();
System.out.println(m.doprocess());
}
}
答案 1 :(得分:1)
您当前的代码无法编译,因为您声明doprocess
方法返回int
但方法正文返回Method
对象。
要使用反射调用方法,请使用invoke。
试试这个:
class myClass {
public Method doprocess() {
dataClass objSt = new dataClass();
Class newCls = objSt.getClass();
Method[] methods = newCls.getMethods();
for (Method method : methods) {
System.out.println(method.getName());
if (method.getName() == "getList") {
return method;
}
}
return null;
}
public static void main(String[] args) {
try {
Method m = new myClass().doprocess();
if(m != null) System.out.println(m.invoke(new dataClass()));
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class dataClass {
public String getList() {
return "hai,";
}
}