Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/388.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用反射时处理或强制转换从方法.invoke()返回的对象_Java_Exception_Object_Reflection_Casting - Fatal编程技术网

Java 使用反射时处理或强制转换从方法.invoke()返回的对象

Java 使用反射时处理或强制转换从方法.invoke()返回的对象,java,exception,object,reflection,casting,Java,Exception,Object,Reflection,Casting,使用Java,我有一个方法,我用返回字符串的method.invoke调用它。 方法.invoke返回一个无法转换为字符串的对象。 我应该如何使用对象作为字符串 在docs on reflection中,它显示了以下内容: Object o = m.invoke(t, new Locale(args[1], args[2], args[3])); out.format("%s() returned %b%n", mname, (Boolean) o); 但我的代码就是这样做的,我得到了一个例外

使用Java,我有一个方法,我用返回字符串的method.invoke调用它。 方法.invoke返回一个无法转换为字符串的对象。 我应该如何使用对象作为字符串

在docs on reflection中,它显示了以下内容:

Object o = m.invoke(t, new Locale(args[1], args[2], args[3]));
out.format("%s() returned %b%n", mname, (Boolean) o);
但我的代码就是这样做的,我得到了一个例外:java.lang.Class不能转换为java.lang.String

这是一个抽象类——然后将有几个bean的实现

            Method[] methods = this.getClass().getMethods();
    for (Method method : methods) {
        if (isMethodGetter(method)) {

            try {

                Object message = method.invoke(this); // expect a string    
                       Object message = method.invoke(this); // expect a string

                if (message == null) {
                    // no messeage
                } else {
                    logger.debug("Calling listAnswers: got an answer: "
                            + message);

                    // create an answer object from the reflected
                    Answer answer = new Answer();
                    answer.setText((String)message);//cast as string
                    answerList.add(answer);
        }

编辑:根据下面的答案,我对验证有问题。非常感谢你在星期六的一个下午帮助我回去工作:)

很简单:你没有得到
java.lang.String
,而是
java.lang.Class
。你在评论中的澄清让一切变得非常清楚:方法
java.lang.Object.getClass
通过了你的
isMethodGetter
测试,但它不是你想要的。只要增强检查代码,就不会让确切的名称通过。

我认为,如果你得到一个ClassCastException,那么你需要检查你调用的方法是否正确。但是为了帮助您,如果您实际上需要一个字符串,那么如果返回的对象不为null,您可能可以调用toString()方法。

没有什么特别的,但是我会为其他有此问题的人编辑这个问题。。。也许我在做一些有趣的事情:)Method[]methods=this.getClass().getMethods();对于(Method:methods){if(isMethodGetter(Method)){try{Object message=Method.invoke(this);//期望一个stringyep,您是100%正确的。我检查了日志,注意到getClass确实显示在调试调试中[com.prevacidecrm.questionaire.model.questionaire listAnswers]=调用列表答案:得到一个答案:class com.prevacidecrm.questionaire.model.impl.PerksEntryQuestionaire.太棒了-谢谢你。这就是我所做的,它是有效的。我很想看看如果需要另一种类型的话,如何正确地做到这一点。@JasonG阅读了我更新的答案。你的情况非常清楚,很容易解决。