Illustration: Cathy Wilcox |
Class
without 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 Class
by passing in its name using something similar to the line below:
1 | Class<?> clazz = Class.forName( "com.bluelotussoftware.example.assignable.SoilentGreen" ); |
Class
, but from here how do we check that it is an instanceof
without instantiating it?This can be solved by using
isAssignableFrom(Class clazz)
as shown below. In this case we are checking if SolientGreen
is Green
. Some of you will find the moral paradox of being "Green" with Soilent Green.
1 2 3 | public static boolean isGreen(Class clazz) { return Green. class .isAssignableFrom(clazz); } |
The second issue is a more potential security problem. How do we load the
Class
without initializing it. If the Class
has a static
initializer, 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 ClassLoader
if you want to specify a specific loader.Finally, we can check the
Class
like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 | public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { Class<?> clazz = Class.forName( "com.bluelotussoftware.example.assignable.StaticInitializerImpl" , false , ClassLoader.getSystemClassLoader()); boolean check = isGreen(clazz); System.out.println( "Passed? " + check); System.out.println( "You shouldn't see: \"The static initializer was called.\"" ); } public static boolean isGreen(Class clazz) { return Green. class .isAssignableFrom(clazz); } |
So here is the remaining code for education and entertainment:
1 2 3 4 5 6 7 | package com.bluelotussoftware.example.assignable; public interface Green { String getFoodType(); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | package com.bluelotussoftware.example.assignable; public class SoilentGreen implements Green { @Override public String getFoodType() { return "people" ; } public boolean isPeople() { return true ; } } |
1 2 3 4 5 6 7 8 9 | package com.bluelotussoftware.example.assignable; public class StaticInitializerImpl { static { System.out.println( "The static initializer was called." ); } } |