繁体   English   中英

从匿名内部类设置外部变量

[英]Setting outer variable from anonymous inner class

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

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

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 服务类中。 显然它不会编译,因为它要求result是最终的,如果是的话——它不会编译,因为我试图修改一个最终的变量。 我必须使用 JDK5。 除了完全删除doWork() ,有没有办法从doWork()设置结果值?

Java 不知道 doWork 将是同步的,并且结果所在的堆栈帧仍然存在。 您需要更改不在堆栈中的内容。

我认为这会奏效

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

进而

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

execute() 最后,你需要return result[0];

这种情况在 Java 中经常出现,最简洁的处理方式是使用简单的值容器类。 它与数组方法的类型相同,但它更干净 IMO。

public class ValContainer<T> {
    private T val;

    public ValContainer() {
    }

    public ValContainer(T v) {
        this.val = v;
    }

    public T getVal() {
        return val;
    }

    public void setVal(T val) {
        this.val = val;
    }
}

你需要一个“容器”来保存你的价值。 但是,您不必创建容器类。 您可以使用java.util.concurrent.atomic包中的类。 它们为值以及setget方法提供了一个不可变的包装器。 您有AtomicIntegerAtomicBooleanAtomicReference<V> (for your objects)

在外部方法中:

final AtomicLong resultHolder = new AtomicLong();

在匿名内部类方法中

long result = getMyLongValue();
resultHolder.set(result);

稍后在您的外部方法中

return resultHolder.get();

这是一个例子。

public Long getNumber() {
   final AtomicLong resultHolder = new AtomicLong();
   Session session = new Session();
   session.doWork(new Work() {
       public void execute() {
           //Inside anonymous inner class
           long result = getMyLongValue();
           resultHolder.set(result);
       }
   });
   return resultHolder.get(); //Returns the value of result
}

长是不可变的。 如果您使用可变类,持有长值,则可以更改该值。 例如:

public class Main {

public static void main( String[] args ) throws Exception {
    Main a = new Main();
    System.out.println( a.getNumber() );
}

public void doWork( Work work ) {
    work.doWork();
}


public Long getNumber() {
    final LongHolder result = new LongHolder();
    doWork( new Work() {
        public void doWork() {
            result.value = 1L;
        }
    } );
    return result.value;
}

private static class LongHolder { 
    public Long value; 
}

private static abstract class Work {
    public abstract void doWork();
}

}

如果包含的类是 MyClass -->

MyClass.this.variable = value;

不记得这是否适用于私有变量(我认为它会起作用)。

仅适用于类的属性(类变量)。 不适用于方法局部变量。 在 JSE 7 中可能会有闭包来做那种事情。

匿名类/方法不是闭包——这正是不同之处。

问题是doWork()可以创建一个新线程来调用execute()并且getNumber()可以在结果设置之前返回 - 甚至更有问题:当包含变量的堆栈帧时, execute()应该在哪里写入结果离开了? 具有闭包的语言必须引入一种机制来使这些变量在其原始范围之外保持活动状态(或确保闭包不在单独的线程中执行)。

解决方法:

Long[] result = new Long[1];
...
result[0] = st.getLong(4) ;
...
return result[0];

对此的标准解决方案是返回一个值。 例如,请参见java.security.AccessController.doPrivileged

所以代码看起来像这样:

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

(还修复了潜在的资源泄漏,并为任何错误返回null 。)

更新:显然Work来自第三方库,无法更改。 所以我建议不要使用它,至少隔离你的应用程序,这样你就不会直接使用它。 就像是:

public interface WithConnection<T> {
    T execute(Connection connnection) throws SQLException;
}
public class SessionWrapper {
    private final Session session;
    public SessionWrapper(Session session) {
        session = nonnull(session);
    }
    public <T> T withConnection(final WithConnection<T> task) throws Service Exception {
        nonnull(task);
        return new Work() {
            T result;
            {
                session.doWork(this);
            }
            public void execute(Connection connection) throws SQLException {
                result = task.execute(connection);
            }
        }.result;
    }
}

从 Hibernate 4 开始,方法Session#doReturningWork(ReturningWork<T> work)将从内部方法返回返回值:

public Long getNumber(final String type, final String refNumber, final Long year) throws ServiceException {
    try {
        Session session = PersistenceHelper.getSession();
        return session.doReturningWork(conn -> {
            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();
            return st.getLong(4);
        });
    } catch (Exception e) {
        log.error(e);
    }
    return null;
}

(使用 Java 8 lambda 清理)

使用AtomicLong在非常相似的情况下帮助了我,代码看起来很干净。

// Create a new final AtomicLong variable with the initial value 0.
final AtomicLong YOUR_VARIABLE = new AtomicLong(0);
...
// set long value to the variable within inner class
YOUR_VARIABLE.set(LONG_VALUE);
...
// get the value even outside the inner class
YOUR_VARIABLE.get();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM