Skip to content Skip to sidebar Skip to footer

How Do I Get A Class Reference From A String In Java?

If I need to return a Class instanced based on a String (e.g., creating logic from JSON), how should that be written? My initial thought was a switch, but in the Android framework'

Solution 1:

Just use Class<?> clazz = Class.forName("com.yourpackage.YourClass") Then to instantiate it: clazz.newInstance();

Solution 2:

You can also load the class with having the constructors parameters.

E.g.

publicstaticvoidload(String p)throws ClassNotFoundException, InstantiationException,
    IllegalAccessException{
        Classcl= classLoader.loadClass(p);
        Constructorc= cl.getConstructor(String.class);
        Pluginplug= (Plugin) c.newInstance("myArgument");
    }

Solution 3:

Your approach using a map is what I would do (and you'll see it in Factory Pattern implementations). You're just not instantiating the class correctly:

ClassclassRef= classMap.get(someString);
SomeSuperClassclassInstance= classRef.newInstance();

Post a Comment for "How Do I Get A Class Reference From A String In Java?"