2013-07-27 50 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

我同意他*不關心,因爲他只是讓你爲他做功課;)然而,其他人搜索對於這個話題的回答可能,因此我的評論。 –