动态实例化抽象子类

时间:2011-09-06 04:11:55

标签: java

首先,我必须说我是Java的新手。所以所有人都道歉,如果我的问题听起来很愚蠢,但到目前为止我还没能找到解决办法......

我想动态实例化一个抽象类的子类。

这是代码

public class CommandMap implements Handler.Callback
{
    private HashMap <Integer, Class<? extends AbstractCommand> > __commandHashMap;

    protected CommandMap()
    {
        __commandHashMap = new HashMap<Integer, Class<? extends AbstractCommand>>();
    }

    /**
     * Map an ID  to a command
     * @param what Id used in the Message sent
     * @param command Command to be executed
     */
    public void mapWhat(Integer what, Class<? extends AbstractCommand> command)
    {
        if ( !__commandHashMap.containsKey(what) )
        {
            __commandHashMap.put(what, command);
        }
    }

    /**
     * Unmap the id/command pair
     * @param what Id
     */
    public void unmapWhat(Integer what)
    {
        if ( __commandHashMap.containsKey(what) )
        {
            __commandHashMap.remove(what);
        }
    }

    public boolean handleMessage (Message message)
    {
    //  call the corresponding command
        if ( __commandHashMap.containsKey(message.what) )
        {
            Class<? extends AbstractCommand> commandClass = __commandHashMap.get(message.what);
            AbstractCommand command = commandClass.getClass().newInstance();
        }
        return true; // for now    
    }
}

这样做的部分

AbstractCommand command = commandClass.getClass().newInstance();

在我的IDE中给出了一个错误(illegalAccessException和InstantiationException)(不是在编译时,因为我还没有尝试过)

所以我用try / catch这样包围它

public boolean handleMessage (Message message)
{
//  call the corresponding command
    if ( __commandHashMap.containsKey(message.what) )
    {
        Class<? extends AbstractCommand> commandClass = __commandHashMap.get(message.what);
        try
        {
            AbstractCommand command = commandClass.getClass().newInstance();
        }
        catch (IllegalAccessException e)
        {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        catch (InstantiationException e)
        {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }
    return true; // for now
}

然后它告诉我类型Class(由newInstance()发送)显然不是AbstractCommand类型。

尝试将Class转换为AbstractCommand时执行

AbstractCommand command = (AbstractCommand) commandClass.getClass().newInstance();

它告诉我Class不能转换为AbstractCommand。

所以我想知道我做错了什么?

再次感谢您提供的任何帮助。

1 个答案:

答案 0 :(得分:4)

我认为你想要的不是

commandClass.getClass().newInstance()

commandClass.newInstance()

commandClass本身就是一个类。因此,在它上面调用getClass()将返回java.lang.Class,如果你要实例化它(你不能,但如果可以的话),它将无法分配给AbstractCommand。但是删除额外的getClass(),你就拥有了命令的类,当你实例化它时,你将获得一个AbstractCommand实例。我认为其他一切似乎都很好。

相关问题