|Illustration: Cathy Wilcox|
Classwithout doing an
instanceof. This turned out to be a great learning experience. There were a couple of issues that needed to be resolved, first we were loading a
Classby passing in its name using something similar to the line below: This will load the
Class, but from here how do we check that it is an
instanceofwithout instantiating it?
This can be solved by using
isAssignableFrom(Class clazz)as shown below. In this case we are checking if
Green. Some of you will find the moral paradox of being "Green" with Soilent Green.
The second issue is a more potential security problem. How do we load the
Classwithout initializing it. If the
staticinitializer, the code is executed when the class is loaded. Alas, this is handled by using a variation of
Class.forName(String name, boolean initialize, ClassLoader loader)which takes a boolean to determine if the class should be initialized, and a
ClassLoaderif you want to specify a specific loader.
Finally, we can check the
Classlike this: When this is run, you will not see the message. Very nice indeed!
So here is the remaining code for education and entertainment:
The code for the project can be downloaded from Bitbucket here: assignable