2
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.

devrobf
  • 6,973
  • 2
  • 32
  • 46
Barnwal Vivek
  • 171
  • 2
  • 11

3 Answers3

6

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.

Mike Strobel
  • 25,075
  • 57
  • 69
4

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.

richardtz
  • 4,993
  • 2
  • 27
  • 38
  • You haven't answered OP's question. He wants to know why A.class.isInterface() and Class.forName("A").isInterface() are returning different values. – Raman Jan 27 '14 at 16:29
  • I think the question was more regarding the output. – Sotirios Delimanolis Jan 27 '14 at 16:29
  • Quoting the OP : "i wan't to know the difference in these two: Class.forName("A") and A.class Thanks a lot." – richardtz Jan 27 '14 at 16:30
  • @richardtz Yes, but the context of that was after he showed "expected output" and "output". – Raman Jan 27 '14 at 16:31
  • Maybe you are right, my answer has already been downvoted several times which I think is not fair. There maybe better answers, in fact I have upvoted another one, but I find a bit disgusting how this happens very frequently. – richardtz Jan 27 '14 at 16:39
0

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
Nambi
  • 11,944
  • 3
  • 37
  • 49