tags:

views:

90

answers:

4

Simple java code snippet. It has three classes. After compiling the code please delete A.class and then execute the code. Code still runs, why its not checking whether the byte code of A exists or not?

class A {
    static {
        System.out.println("In the class A");
    }

    public A() {
    }
}

class B {
    private A a = null;

    static {
        System.out.println("In the class B");
    }

    public B() {
        a = new A();
    }
}

public class ExampleLinkage {
    static {
        System.out.println("In the class A");
    }

    public ExampleLinkage(String str) {
    }

    public static void main(String args[]) {
        try {
            System.out.println("In the main method of ExampleLinkage");
            Class.forName("com.bt.rtti.B");
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}
+1  A: 

As your not recompiling it, just running the class.

Gordon
I don't understand this answer. Recompiling would need the .java file, not the .class file.
Thomas Padron-McCarthy
Just making the point the JRE doesn't check if complied classes exist only the complier searches for sources files or complied classes in the class path.
Gordon
A: 

Class A is not used in the code (i.e. in the main method).

At run-time classes are loaded as they are being used. At that time, you would get a ClassNotFoundError. But if you are not using the class, there is not need for it to be there.

Try to make an instance of B (which needs an instance of A), then you will get an error.

Thilo
A: 

Further to Gordon's answer, you are only running the class, and class A is not required, if you called A's constructor or referenced a static field or method in A, then you would get the ClassNotFoundException you are expecting

James B
+5  A: 

I would guess that at no point the class A is needed to be loaded, even though there is an instance of it inside B, since you never instantiate an instance of B.

the JVM is very lazy when it load classes. it loads them either when you instantiate an object of that class (at the first time), when you explicitly load a class with Class.forName() or when you otherwise reference the class in a way that requires information from it (try accessing a static member of A from the static initializer of B and see that A will get loaded.

Omry