gpt4 book ai didi

java - 动态实例化抽象子类

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:24:53 26 4
gpt4 key购买 nike

首先我不得不说我是 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
}

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

当尝试将 Class 转换为 AbstractCommand 时

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

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

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

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

最佳答案

我想你想要什么而不是

commandClass.getClass().newInstance()

commandClass.newInstance()

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

关于java - 动态实例化抽象子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7314838/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com