java - 在 Java SwingWorker 方法的签名中使用最终变量

标签 java scope final swingworker

I have a method that uses a SwingWorker.   Part of the code is shown below:

   public class mySocket {

   public void writePacket(final String packet) {
    // schedules execution on the single thread of the executor (so only one
    // background operation can happen at once)
    //
    executor.execute(new SwingWorker<String, Void>() {

        @Override
        protected String doInBackground() throws Exception {
            // called on a background thread
            System.out.println("writing out this packet->" + packet + " 
                            <-");
            out.println(packet);
            String thePacket = readPacket();
            return thePacket;
        }

                ..................

我的问题是关于 writePacket 方法的签名。变量 packet 必须声明为 final 否则编译器会报错,因为 SwingWorker 是一个内部类。这引发了以下关于如何以及何时可以为该变量赋值的问题:

  1. Final 对我来说意味着变量只能赋值一次。但是因为声明是方法签名的一部分,所以我不知道在这种情况下这意味着什么。
  2. 我一直假设最终变量在类被实例化时被赋值,但在这里它是在调用方法时被赋值的。传递给方法的变量是否也需要声明为 final 并在类的构造函数中分配才能工作?
  3. 我是否可以使用不同的 packet 值多次调用该方法,或者因为变量被声明为 final,这是否意味着如果我想使用不同的值调用该方法,我需要为每个新值重新实例化该类变量数据包?

预先感谢您的帮助。

埃利奥特

最佳答案

1. Final to me means that the variable can only be assigned a value once. But because the declaration is part of the signature of a method, I don't know what this means in this context.

这只是意味着您不能将新值重新分配给变量packet

2. I always assumed that final variables were assigned values when the class was instantiated but here it is assigned when the method is called. Does the variable passed to the method also need to be declared final and assigned in the class's constructor for this to work?

您也可以拥有本地 final 变量。相同的规则适用,但它们与构造函数/this 引用无关。

3. Can I call the method more than once with different values for packet or because the variable is declared final, does this mean that if I want to call the method with different values, I need to reinstantiate the class for each new value of the variable packet ?

您可以使用不同的值多次调用该方法。 packet 变量就像一个局部变量。不,您不需要为每个值/调用重新实例化该类。

进一步阅读:

关于java - 在 Java SwingWorker 方法的签名中使用最终变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7332300/

相关文章:

java - 添加到数组列表

java - 创建更大的数组后,如何在同一类的其他函数中使用新数组?

javascript - 如何在 JavaScript 中创建全局变量?

java - 我在本学期的最后一个实验中无法正确读取文件,并且在读取实际文件时不断遇到问题

java - JButton 数组上的 ActionListener

来自字符串的 Java 星期几

java - 使用onMouseClicked方法时如何获取ImageView的ID?

javascript - JavaScript 回调的效率

c - 从另一个文件访问的 C 中的静态变量

Java错误: <identifier> expected: "date"