2013-07-27 31 views
-5
class Clasa {...} 

class Test { 

    public static void main(String[] args){ 

     Clasa x = new Clasa(); 
     System.out.println(x.getNo());//displays 1 
     Clasa[] y = new Clasa[10]; 
     for(int i = 0; i<4; i++) 
      y[i]=new Clasa(); 
     System.out.println(y[0].getNo()); //displays 5 
    } 
} 

如何替换这三个点,因此GetNo()方法调用返回Clasa类的实例化对象的数量。测试课不应该改变。获取Java中实例化对象的数量

+0

@hexafraction:你为什么会在这个地方使用反射? (并且,对于这个问题 - *你会如何在地球上使用反射?) – ruakh

+0

尝试一些逻辑,如果它不起作用,那么寻求帮助。尽量不要直接询问逻辑或代码。 – JNL

+0

@hexafraction他并不是只希望所有的java实例'Clasa类的实例化对象的数量。 –

回答

0

我同意布赖恩,在上面的代码是不考虑GC的所有实例。所以我想用下面的代码片段

package com.instance.main; 
import com.instance.target.Clasa; 

    public class Test{ 

     public static void main(String[] args) { 

     Clasa targetClass; 
     Object[] object=new Object[10]; 
     for(int i=0;i<object.length;i++){ 
      object[i]=new Clasa(); 
     } 

     System.out.println("Number of Instantiate Object {Before Calling GC}: "+Clasa .getNumberOfInstatiateObj()); 

     /* Here I am trying to deallocate the memory of Object at index no 9, so that GC called this unused object to deallocate it from memory*/ 
     for(int i=0;i<object.length;i++){ 
      if(i==8){ 
       object[i]=object[i+1]; 
       object[i+1]=null; 
       System.runFinalization(); 
       System.gc(); 
      } 
     } 

     } 
    } 

更换你的代码只是把上面的代码的主要方法之下,你也必须从下面的代码

包com.instance修改Clasa代码。目标;

类Clasa {

private static int nbInstances = 0; 

    public Clasa() { 
     nbInstances++; 
    } 

    public int getNo() { 
     return nbInstances; 
    } 

    public void finalize(){ 
     nbInstances --; 
     System.out.println("Number of Instantiate Object {After Calling GC}: "+nbInstances); 
    } 

}

按照上述步骤修改您的代码后,你的代码就会给你所需的输出。

请让我纠正,如果我错了,在哪里。

嗨Dany我修改了我的代码,所以根据上面的代码,你必须创建你的类下不同的包,写在类代码。如果您仍然遇到问题,请告诉我。

+0

我不同意你:) 他显然是Java的初学者。他应该逐步学习。尽管你的代码有很多Java的高级功能,但它会吓到他...... –

+0

另外,你放置你的解决方案的方式并不能帮助他,因为你告诉他在不知道它做什么的情况下使用代码 –

+0

@Adel ,你是对的,我没有提供关于上述代码的很多信息。 – Ashish

4

添加一个作为计数器的静态变量,并在构造函数中增加它,并返回静态变量的值。

静态变量有自己的价值观保持一类

class Clasa { 

    private static int nbInstances = 0; 

    public Clasa() { 
     nbInstances++; 
    } 

    public int getNo() { 
     return nbInstances; 
    } 
} 
+1

值得注意的是,它不是线程安全的,当对象获得GC'd时,它当然不会减少。 –

+0

@BrianRoach从他的代码和问题,我不认为他关心GC和递减 –

+0

我同意他*不关心,因为他只是让你为他做功课;)然而,其他人搜索对于这个话题的回答可能,因此我的评论。 –