0

When I have a lot of type checks in Java like this:

if (clazz.equals(Byte.class) <dosomething>
if (clazz.equals(Integer.class) <dosomething>
...

Does the JVM load all these class (Byte, Integer?) And if it does, is there another way to do class type checking without loading a bunch of classes I might not even need?

dertoni
  • 1,763
  • 2
  • 24
  • 47

4 Answers4

6

Yes, using .class will load the class, but don't worry about these -- everything in java.lang is going to already be loaded before your program even runs, because these classes are all either used by the JVM itself, or used by other API classes that are pre-loaded.

If you wanted to check for a class without loading the class, you could do something like

if (clazz.getName().equals("com.foo.MyClass")) ...

but that would be rather fragile; I'd avoid it unless there was a really good reason.

Anyway, start Java with -verbose:class sometime to see all the classes that are pre-loaded for you!

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
  • 1
    I'd recommend against using getName(), etc. as it fails in 2 ways - first that it's not classloader aware (it flattens the namespace) and second, string compares are clunky relative to what the code that the original will do. (which could boil down to almost no code when the JIT gets into it.) (yes, the string compare will be fast as it's got optimizations too, but it's still not great.) – Trent Gray-Donald Aug 24 '11 at 14:19
1

You can easily get an answer to this question by testing what happens if you write:

if (c.equals(No.such.class)) ....
Ingo
  • 36,037
  • 5
  • 53
  • 100
1

Any class you explicitly reference inside another class gets loaded by the classloader. And get this...whatever classes those classes explicitly reference, will get loaded by the classloader. So, essentially no. If you reference it, it will get loaded.

Chris Aldrich
  • 1,904
  • 1
  • 22
  • 37
  • 1
    Note that `import` is a directive to the compiler and has precisely zero effect on generated code; i.e., unused imports do *not* cause anything to be loaded. – Ernest Friedman-Hill Aug 24 '11 at 12:42
  • really? cause from what I've seen when debugging code with classloaders is I've watched the classloaders run over the list of "imported/referenced classes" and go load those in order to load one class. Of course I work with IBM stuff a lot, so we are working with their JVM and who knows how they implement their stuff compared to Sun/Oracle. But I was under the impression imports did play into class loaders. Could you provide documentation? – Chris Aldrich Aug 24 '11 at 12:53
  • Never mind, I found it here: http://stackoverflow.com/questions/2903166/meaning-of-import-statement-in-java-file – Chris Aldrich Aug 24 '11 at 13:00
1

I really wouldn't care about that, but if you really worry, you can do something like this instead:

if (clazz.getName().equals("java.lang.Integer")) // do something
Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268