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?

4 Answers 4

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!

Sign up to request clarification or add additional context in comments.

1 Comment

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.)
1

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

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

Comments

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

Comments

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.

3 Comments

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.
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?
Never mind, I found it here: stackoverflow.com/questions/2903166/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.