加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

在Java SwingWorker方法的签名中使用final变量

发布时间:2020-12-15 08:43:25 所属栏目:Java 来源:网络整理
导读: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 operati
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方法的签名.变量包必须声明为final或编译器抱怨,因为SwingWorker是一个内部类.这引发了以下关于如何以及何时可以为此变量赋值的问题:

>对我而言,意味着变量只能被赋值一次.但由于声明是方法签名的一部分,我不知道这在这种情况下意味着什么.
>我总是假设在实例化类时为最终变量赋值,但是在调用方法时分配它.传递给方法的变量是否也需要声明为final并在类的构造函数中赋值以使其工作?
>我可以使用不同的数据包值或者因为变量被声明为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.

它只是意味着您无法将新值重新分配给变量数据包.

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?

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

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 ?

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

进一步的SO阅读:

> Cannot refer to a non-final variable inside an inner class defined in a different method
> Cannot refer/modify non-final variable in an innerclass
> access to variable within inner class in java

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读