简体   繁体   English

根据传递的字符串创建和返回对象

[英]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? 有什么方法可以基于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. 我想创建作为Package类的子类的对象,并通过调用传递类名的方法来实现。 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. 我可以很容易地用switch语句来完成此操作,但是如果我这样做,当我添加Packages的更多子类时,我就不必调整switch语句。

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. 我正在编写Android代码,但是在这种情况下我认为这没有什么不同。

You have a NullPointerException because you don't initialize testPackage . 您有一个NullPointerException,因为您没有初始化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). 因此,我相信您的问题是,您永远不会在方法中分配变量curPackage (至少从我所编写的代码中可以看出)。 You need to assign your testPackage, ie: 您需要分配您的testPackage,即:

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

At this point you can just remove your Object parameter since its never used in the method. 此时,您可以删除Object参数,因为它从未在方法中使用过。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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