如何摆脱我的java代码中的静态变量?

时间:2015-02-03 17:19:29

标签: java

专家:

我会问一个可能听起来很愚蠢的问题。我需要使用类静态变量删除,这是一个高级队友的反击。他说我应该只在必要时使用静态成员,这是线程不安全的。我只能弄清楚是使用同步关键字。我想知道是否有更好的解决方案。以下是我目前的代码。

package gov.faa.infra.ifp.domain.dao.isc;

import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertNotNull;

import java.util.List;

import org.apache.log4j.Logger;

import gov.faa.infra.ifp.message.MessageCollectionBean;

public abstract class IdentifiableTest<T>{

private static int recordedMessageLength=0; 
private static Logger logger = Logger.getLogger(IdentifiableTest.class.getName());

abstract public void checkIndividualIdentifiable(T identifiableObject);

public void checkIdentifiable(T identifiableObject){
    checkMessageCollection();
    checkIndividualIdentifiable(identifiableObject);
}

public void checkIdentifiableList(List<T> identifiableList){
    checkMessageCollection();
    assertNotNull(identifiableList);
    assertTrue(identifiableList.size()>0);

    for (int i=0; i<identifiableList.size(); i++){          
        checkIndividualIdentifiable(identifiableList.get(i));
    }
}

public void checkMessageCollection(){

    if (MessageCollectionBean.getMessages()!=null){
        if (MessageCollectionBean.getMessages().length>recordedMessageLength){
            int i=MessageCollectionBean.getMessages().length-1;
            for (String message: MessageCollectionBean.getMessages()){
                if(i>=recordedMessageLength){
                    logger.debug(message+"##"+i+"th message in the total of "+MessageCollectionBean.getMessages().length+" messages. recordedMessageLength="+recordedMessageLength+"####Message Collection Bean");
                }
                i--;
            }
            recordedMessageLength=MessageCollectionBean.getMessages().length;
        }
    }

    assertTrue(MessageCollectionBean.getMessages()==null || MessageCollectionBean.getMessages().length==recordedMessageLength);
}

}

1 个答案:

答案 0 :(得分:0)

看起来它是由checkMessageCollection()计算的,因此请将其作为方法调用的结果。