Is there any way to create and return an object based on a passed string in Java? I want to create objects that are subclasses of a Package class, and do this by calling a method that passes the class name. I could accomplish this with a switch statement easily enough, but if I do it this way, when I add more subclasses of Packages I won't have to adjust the switch statement.
Here's what I have for code:
Package Variable:
private Package testPackage;
Method Call:
createPackage(testPackage, "TestPackage");
And the method:
Object createPackage(Object curPackage, String packageName)
{
Object object = null;
try
{
Class<?> aClass = Class.forName("a.b.c.packages." +packageName);
Constructor<?> constructor = aClass.getConstructor(new Class[] { String.class });
object = constructor.newInstance(new Object[] { packageName });
} catch (Exception e)
{
e.printStackTrace();
}
return object;
}
The class is found, but after I run this method and try to call
Log.v(TAG, testPackage.getName());
I get a null pointer exception. I am writing Android code, I don't think that makes a difference in this situation, though.