heivik
heivik

Reputation: 111

About loading Class instances in 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");

Upvotes: 3

Views: 101

Answers (2)

Vishal
Vishal

Reputation: 3279

This code should always print true. As you are pointing to the same class by using p1.getClass()

identityHashCode

public static int identityHashCode(Object x)
Returns the same hash code for the given object as would be returned by the default method hashCode(), whether or not the given object's class overrides hashCode(). The hash code for the null reference is zero.
Parameters:
x - object for which the hashCode is to be calculated
Returns:
the hashCode
Since:
JDK1.1

As per the description written above, it will give default hashCode value which is always be different in object instantiation...

Person is an instance of Class class, so P1.getClass and P2.getClass are pointing to same instance of class... So V1 == V2.

Upvotes: 0

Jens Schauder
Jens Schauder

Reputation: 81882

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?

Upvotes: 1

Related Questions