从匿名内部类设置外部变量 [英] Setting outer variable from anonymous inner class

查看:281
本文介绍了从匿名内部类设置外部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法从Java中的匿名内部类访问调用者范围的变量?

Is there any way to access caller-scoped variables from an anonymous inner class in Java?

以下是了解我需要的示例代码:

Here's the sample code to understand what I need:

public Long getNumber(final String type, final String refNumber, final Long year) throws ServiceException {
    Long result = null;
    try {
        Session session = PersistenceHelper.getSession();
        session.doWork(new Work() {
                public void execute(Connection conn) throws SQLException {
                    CallableStatement st = conn.prepareCall("{ CALL PACKAGE.procedure(?, ?, ?, ?) }");
                    st.setString(1, type);
                    st.setString(2, refNumber);
                    st.setLong(3, year);
                    st.registerOutParameter(4, OracleTypes.NUMBER);
                    st.execute();
                    result = st.getLong(4) ;
                }
            });
    } catch (Exception e) {
        log.error(e);
    }
    return result;
}

代码位于DAO服务类中。显然它不会编译,因为它要求结果是最终的,如果是 - 它不会编译,因为我尝试修改最终的var。我一定是JDK5。除了完全放弃 doWork()之外,有没有办法在 doWork()中设置结果值?

The code is in a DAO service class. Obviously it doesn't compile, because it asks that result be final, if it is -- it doesn't compile because I try to modify a final var. I'm bound to JDK5. Other than dropping the doWork() altogether, is there a way to set the result value from within doWork()?

推荐答案

Java不知道doWork将是同步的,并且结果所在的堆栈帧仍然存在。你需要改变不在堆栈中的东西。

Java doesn't know that doWork is going to be synchronous and that the stack frame that result is in will still be there. You need to alter something that isn't in the stack.

我认为这样可行

 final Long[] result = new Long[1];

然后

 result[0] = st.getLong(4);

in execute()。最后,你需要返回结果[0];

in execute(). At the end, you need to return result[0];

这篇关于从匿名内部类设置外部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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