我同意布赖恩,在上面的代码是不考虑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类的实例化对象的数量。 –