在Java SwingWorker方法的签名中使用final变量
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是一个内部类.这引发了以下关于如何以及何时可以为此变量赋值的问题: >对我而言,意味着变量只能被赋值一次.但由于声明是方法签名的一部分,我不知道这在这种情况下意味着什么. 在此先感谢您的帮助. 埃利奥特 解决方法
它只是意味着您无法将新值重新分配给变量数据包.
您也可以拥有本地最终变量.适用相同的规则,但它们与构造函数/此引用无关.
您可以使用不同的值多次调用该方法.数据包变量就像一个局部变量.和否,您不需要为每个值/调用重新实例化该类. 进一步的SO阅读: > Cannot refer to a non-final variable inside an inner class defined in a different method (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |