我同意布賴恩,在上面的代碼是不考慮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我修改了我的代碼,所以根據上面的代碼,你必須創建你的類下不同的包,寫在類代碼。如果您仍然遇到問題,請告訴我。
@hexafraction:你爲什麼會在這個地方使用反射? (並且,對於這個問題 - *你會如何在地球上使用反射?) – ruakh
嘗試一些邏輯,如果它不起作用,那麼尋求幫助。儘量不要直接詢問邏輯或代碼。 – JNL
@hexafraction他並不是只希望所有的java實例'Clasa類的實例化對象的數量。 –