简体   繁体   中英

Create and Return an Object Based on a Passed String

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.

You have a NullPointerException because you don't initialize testPackage .

And you have to cast the result :

 testPackage = (Package)createPackage("TestPackage")

(and you can remove the first parameter, which is not used)

So I believe your problem is that you never assign your variable curPackage in your method (at least from what I can tell with the code you've written). You need to assign your testPackage, ie:

private Package testPackage = (Package) createPackage("TestPackage");

At this point you can just remove your Object parameter since its never used in the method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM