这可能是一个愚蠢的问题,但它已经让我发疯好几天了。 首先,我谈论的是嵌入到较大应用程序中的代码,因此强加了类和方法签名。
所以我的目标是创建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()) );
好吧...我迷路了。感谢您的任何提示。
劳伦特
最佳答案
您正在尝试在 JVMMemStats()
静态方法内创建非静态
内部类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
}
关于java - 将对象添加到静态集合中以用于静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16627399/