java - 将对象添加到静态集合中以用于静态方法

标签 java dictionary static

这可能是一个愚蠢的问题,但它已经让我发疯好几天了。 首先,我谈论的是嵌入到较大应用程序中的代码,因此强加了类和方法签名。

所以我的目标是创建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/

相关文章:

java - GL15在lwjgl里坏了

android - onTap 如何在 android mapview 中工作

c++ - 了解类构造函数的静态转换

java - 如何理解 "Every Class object contains a reference to the ClassLoader that defined it. "?

java - 不知道如何实现仅最后一个节点作为引用的循环链表

python - 检查字典数组中的键值对并相应更新另一个列表

android - 是否可以在静态上下文 block 中获取资源?

javascript - @SpringBootApplication 不加载静态文件

java - SQL SERVER 2008-无法获取 ddl 架构中少数对象的对象定义?

字典列表的 Python 集合计数器