Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About loading Class instances in Java

Tags:

java

Is it possible that following code prints "false"?

If it is possible that object of type Class may be loaded then unloaded and then reloaded during execution of program then this could print false ?

Is the situation same in android and "normal java" ?

    class Person
    {
      Integer age;
      Person(Integer age) {this.age=age;}
    }

    int v1;
    {
      Person p1 = new Person(5);
      v1 = System.identityHashCode(p1.getClass());
    }
    .
    .

    int v2;
    {
      Person p2 = new Person(10);
      v2 = System.identityHashCode(p2.getClass());
    }


    if (v1 == v2)
      System.out.println("true");
    else
      System.out.println("false");
like image 614
heivik Avatar asked Dec 06 '25 06:12

heivik


1 Answers

If all the code (except the class definition of Person is in a single class I don't think it can get two different instances of the Person class.

If you use something like OSGI you can actually get the Person-class loaded multiple times by different classloaders, and their hashCodes would be different, so I guess:

Yes you can construct cases where this returns "false"

Since you don't keep a reference to the Person instances the class could in theory actually get unloaded, when the two instanciating pieces themselves get loaded via reflection and garbage collected afterwards. AFAIK nothing in the language specification prevents garbage collections of class definitions. This is tremendously important when you have e.g. a web container where you deploy new versions of classes all the time during development. If the old versions don't get garbage collected this will lead to memory issues.

See also:

Unloading classes in java?

How to unload an already loaded class in Java?

like image 58
Jens Schauder Avatar answered Dec 09 '25 17:12

Jens Schauder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!