2013-05-18 45 views
1

可能是一個愚蠢的問題,但它在一些日子裏一直讓我瘋狂。首先,我講的是嵌入在更大的應用程序中的代碼,所以類和方法簽名是強加的。將一個對象添加到靜態方法的靜態集合中

所以我的目標是創建的GC信息的集合,代碼如下:

public final class JVMMemStats_SVC { 
    public static final void JVMMemStats(IData pipeline) throws ServiceException { 
     List<GarbageCollectorMXBean> gcMBeans = ManagementFactory.getGarbageCollectorMXBeans(); 
     for (GarbageCollectorMXBean gcBean : gcMBeans){ // Loop against GCs 
      GC gc = GCs.get(gcBean.getName()); 
      if(gc != null){ // This GC already exists 

      } else { // New GC 
       GCs.put(
        gcBean.getName(), 
        new GC(gcBean.getCollectionCount(), gcBean.getCollectionTime()) 
       ); 
      } 
    } 

    public class GC { 
     public long Cnt, Duration; 

     public GC(long cnt, long duration){ 
      this.set(cnt, duration); 
     } 

     public void set(long cnt, long duration){ 
      this.Cnt = cnt; 
      this.Duration = duration; 
     } 
    } 

    static Map<String, GC> GCindexes = new HashMap<String, GC>(); 
} 

但是我在編譯時出現以下錯誤:

non-static variable this cannot be referenced from a static context : 
    GCPrev.add(new GC(gcBean.getCollectionCount(), gcBean.getCollectionTime())); 

嗯...我迷路了。感謝您的任何提示。

Laurent

+0

什麼是GCPrev? – Bathsheba

回答

0

您正試圖在JVMMemStats()靜態方法內創建一個non-static內部類GC的實例。

non-static variable this cannot be referenced from a static context : 
    GCPrev.add(new GC(gcBean.getCollectionCount(), gcBean.getCollectionTime())); 

上面提到的靜態上下文是JVMMemStats()方法。只需將類別聲明更改爲

public static class GC { 
    // needs to be static to be instantiated in a static method 
} 
+0

謝謝拉維,它工作得很好。 – destroyedlolo

+0

@destroyedlolo我很高興它的工作。如果有幫助,請考慮接受答案。謝謝。 –

+0

完成,再次感謝。 – destroyedlolo

0

非靜態變量,方法不能從靜態方法訪問。因此將靜態變量更改爲非靜態或將非靜態方法更改爲靜態和檢查。