我有一个带有此静态变量的帮助程序类,该变量用于在两个类之间传递数据。

public class Helper{
    public static  String paramDriveMod;//this is the static variable in first calss
}


此变量用于以下第二类数学方法

    public void USB_HandleMessage(char []USB_RXBuffer){
    int type=USB_RXBuffer[2];
    MESSAGES ms=MESSAGES.values()[type];
    switch(ms){
        case READ_PARAMETER_VALUE:  // read parameter values
            switch(prm){
                case PARAMETER_DRIVE_MODE:  // paramet drive mode
                    Helper.paramDriveMod =(Integer.toString(((USB_RXBuffer[4]<< 8)&0xff00)));
                    System.out.println(Helper.paramDriveMod+"drive mode is selectd ");
                    //here it shows the value that I need...........
            }
    }
    //let say end switch and method
}


以下是使用上述类方法的第三类方法

public void buttonSwitch(int value) throws InterruptedException{
    boolean bool=true;
    int c=0;
    int delay=(int) Math.random();
    while(bool){
        int param=3;
        PARAMETERS prm=PARAMETERS.values()[param];
        switch(value){
            case 0:
                value=1;
                while(c<5){
                    Thread.sleep(delay);
                    protocol.onSending(3,prm.PARAMETER_DRIVE_MODE.ordinal(),dataToRead,dataToRead.length);//read drive mode
                    System.out.println(Helper.paramDriveMod+"  drive mode is ..........in wile loop");//here it shows null value
                }
                //break; ?
        }
    }
    //let say end switch and method
}


该变量失去其值的原因是什么?

最佳答案

我可以建议在类之间传递数据时,使用单独的对象而不是全局变量吗?

完全不清楚您希望如何执行protocolImpl中的代码-正如templatetypedef所提到的,您没有在那个类或param类中显示有效的Java代码(这两个代码都不遵循Java命名约定)。

一个简短但完整的示例确实会有所帮助,但总的来说,我建议您首先避免使用此模式。考虑对象而不是全局变量。

关于java - 静态变量失去值(value),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4698652/

10-12 00:42
查看更多