Programming Tips - Java: Load (make an instance) of a class that is compiled in with my program

Date: 2013oct21 Update: 2025oct21 Language: Java Keywords: plugin Q. Java: Load (make an instance) of a class that is compiled in with my program A. Of course you can do:
Class<?> cls = null; if (something1) { cls = new MyClass1; } else if (something2) { cls = new MyClass2; }
But if you don't want to hardcode names use reflection. Here is a full example:
class Demo { static Class<?> loadMyClass(String name) { final String classname = "com.mycompany.myprogram." + name; try { return Class.forName(classname); } catch (Exception ex) { System.err.println("Could not load '" + classname + "' because " + ex.getMessage()); return null; } } public static final void main(String []args) { Class<?> plugin = loadMyClass("plugin"); System.out.println("plugin=" + plugin): } }
Output (example):
plugin=Name@7f9fcf7f