Java:InvocationTargetException [英] Java: InvocationTargetException

查看:665
本文介绍了Java:InvocationTargetException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中动态创建类并尝试调用它们中的方法,但是,有时我会得到 java.lang.reflect.InvocationTargetException

I am dynamically creating classes in Java and trying to invoke methods in them, however, sometimes I get a java.lang.reflect.InvocationTargetException.

PageGenerator1.java(动态创建)

import java.io.PrintStream;
import java.util.Map;
public class PageGenerator1 implements DynamicPageGenerator {
    public PageGenerator1() {
    }

    @Override
    public void generate(PrintStream out, Map<String,String> params, Session session) {
        out.print("<html>\r\n<body>\r\n");
        if (session.get("counter") == null) {
                session.set("counter", 2);
                out.println("<h1>Hi "+params.get("name")+" this is your first visit</h1>");
        } else {
                out.println("<h1>This is your "+session.get("counter")+" visit</h1>");
                session.set("counter", 1+((Integer)session.get("counter")));
        }
        out.print("\r\n</body>\r\n</html>");
    }
}

我试图像这样调用它:

    logger.info(
        "Attempting to invoke the method " + generateMethod + " with an instance of " + generatedClassName + "with the following parameters:\n" +
            "\tparams: " + params + "\n" +
            "\tcookieSession: " + cookiesSession
    );

    generateMethod.invoke(Class.forName(generatedClassName).newInstance(), ps, params, cookiesSession);

这是我得到的日志条目:

and this is the log entry I get:


INFO:尝试调用方法

public void cs236369.webserver.requesthandlers.tsp.PageGenerator1.generate(java.io.PrintStream, java.util.Map,cs236369.webserver.requesthandlers.tsp.Session)

,实例为
cs236369.webserver .requesthandlers.tsp.PageGenerator1

包含以下参数:

params: {name = Amir}

cookieSession: {counter = 5}

我得到的例外没有消息,我没有反思等经验,所以我不确定错误是什么意思。你能帮我解释一下我做错了什么吗?

The exception I'm getting doesn't have a message, and I'm not experienced with reflection, etc. so I'm not sure what the error means. Can you help explain what am I doing wrong?

推荐答案

InovcationTargetException意味着你调用的方法引发了异常。要弄清楚你的方法本身有什么问题,请在try-catch块周围包装invoke方法调用并记录 invocationTargetException.getTargetException()

InovcationTargetException means that the method that you invoked threw an exception. To figure out what the problem is with your method itself, wrap the invoke method call around a try-catch block and log invocationTargetException.getTargetException().

我可以在你的generateMethod中看到你可能有错误的几个地方。 Session可以为null,session.getCounter()被强制转换为Integer - 那里可能有classcastexception。

I can see several places in your generateMethod that you could have errors. Session could be null, session.getCounter() is being cast to Integer -- there could be a classcastexception there.

这篇关于Java:InvocationTargetException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆