dertoni
dertoni

Reputation: 1803

Class loading behaviour when using Byte.class

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?

Upvotes: 0

Views: 75

Answers (4)

Chris Aldrich
Chris Aldrich

Reputation: 1932

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.

Upvotes: 1

Andreas Dolk
Andreas Dolk

Reputation: 114847

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

Upvotes: 1

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81734

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!

Upvotes: 6

Ingo
Ingo

Reputation: 36339

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

if (c.equals(No.such.class)) ....

Upvotes: 1

Related Questions