Barnwal Vivek
Barnwal Vivek

Reputation: 169

Reflection API, Class.forName() vs .class

interface A {
}

public class B {
    public static void main(String a[]) {
        Class c = Class.forName("A");
        System.out.println(c.isInterface());//false
        Class c1 = A.class;
        System.out.println(c1.isInterface());//true
    }
}

o/p: false true

expecting o/p: true true

i wan't to know the difference in these two: Class.forName("A") and A.class Thanks a lot.

Upvotes: 2

Views: 3023

Answers (3)

Mike Strobel
Mike Strobel

Reputation: 25623

Class.forName() attempts to resolve a class at runtime, using the default class loader. It may succeed, or it may fail, depending on whether the desired class is valid and within your classpath.

The .class operator evaluates the class descriptor as a compile-time constant. It can still fail at runtime if the referenced class is not valid and present within the classpath, but it can be used in places where constant expressions are required (e.g., in annotation values), and it is generally more resilient with respect to refactoring. Note that the class descriptor that is captured depends on the compiler's inputs and classpath; with different compiler arguments, the same code may end up referencing two different classes.

In your use case, both should resolve to the same class. Your results are unexpected, and may indicate the presence of another class named A within your classpath. I suspect the interface A that you quoted in your question is actually located within a package, in which case you are passing the wrong descriptor to forName(). The name should be package-qualified.

Upvotes: 6

Nambi
Nambi

Reputation: 12040

it gives Runtime error surround with try and catch or throws in java

Do like this, to get true true

interface A{
}

public class B{
public static void main(String a[]) throws ClassNotFoundException{
Class c= Class.forName("A");
System.out.println(c.isInterface());
Class c1=A.class;
System.out.println(c1.isInterface());
}
}

Output

true
true

Upvotes: 0

richardtz
richardtz

Reputation: 4993

If you write A.class the compiler needs to know A at compile time.

If you write Class.forName("A"), then it is only needed at runtime.

Upvotes: 4

Related Questions