Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/344.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将对象添加到静态方法的静态集合中_Java_Map_Static - Fatal编程技术网

Java 将对象添加到静态方法的静态集合中

Java 将对象添加到静态方法的静态集合中,java,map,static,Java,Map,Static,也许是个愚蠢的问题,但这几天来一直让我发疯。 首先,我要说的是嵌入在更大应用程序中的代码,因此类和方法签名是强制的 因此,我的目标是创建一个GC信息集合,代码如下: public final class JVMMemStats_SVC { public static final void JVMMemStats(IData pipeline) throws ServiceException { List<GarbageCollectorMXBean> gcMB

也许是个愚蠢的问题,但这几天来一直让我发疯。 首先,我要说的是嵌入在更大应用程序中的代码,因此类和方法签名是强制的

因此,我的目标是创建一个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>();
}
嗯。。。我迷路了。谢谢你给我小费


Laurent

非静态变量,无法从静态方法访问方法。因此,将中的静态变量更改为非静态,或者将非静态方法更改为静态并检查。

您正在尝试在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
}

@我很高兴它成功了。如果有帮助的话,请考虑接受这个答案。谢谢
public static class GC {
     // needs to be static to be instantiated in a static method
}