I am using the Wrapper Class method to allow me to handle a class either existing or not. When using this technique, it is important to know what will cause my Proxy class to be initialized. In particular, what if I:
-
Declare an instance of
Proxywithout setting it to anythingpublic class myClass{
…
Proxy myInst;
} -
Declaring an instance of
Proxylocally inside a never run if statementpublic void myMeth{
if(ProxyIsAvailableWhichItIsNot){
Proxy myInst;
…
}
}
Update: As pointed out by Henning, I am interested in when a class is initialized (and static blocks run), rather than when it is loaded. I updated the question to reflect this.
A Java implementation has a choice of either loading a class as soon as another class that references it is loaded, or postponing this until it becomes necessary to initialize the class. In the first case, the class can sit around for a considerable amount of time (perhaps forever) being loaded but not initialized.
In contrast, there are precise rules for when a class is initialized (static initializers run), namely the first time an object of the class is created, or a static method called, or a non-constant static field is accessed.
The only completely sure way to prevent a JVM from trying to load a class is not to mention it explicitly in the code and use
Class.forName()and reflection to request loading at some definite point in time, at which timeClassNotFoundExceptionmay be thrown and handled. However, modern JVMs typically load classes much more lazily than the language specification allows them to, so more optimistic strategies will often work in practice.The “wrapper class” technique described in your link is not guaranteed to work by Java (see §12.1.2 of the Java Language Specification, 3rd edition), but it’s entirely possible that Android/Dalvik gives stronger guarantees of its own.