开发者

Class loading behaviour when using Byte.class

开发者 https://www.devze.com 2023-03-30 15:45 出处:网络
When I have a lot of type checks in Java like this: if (clazz.equals(Byte.class) <dosomethin开发者_开发技巧g>

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

if (clazz.equals(Byte.class) <dosomethin开发者_开发技巧g>
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?


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!


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

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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号