-1

我有以下类,当我调用 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 函数的返回值

4

2 回答 2

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());
    }

}
于 2013-03-06T02:57:10.537 回答
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,";
    }
}
于 2013-03-06T02:57:28.150 回答