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和InstanceionException)(不是在编译时,因为我还没有尝试过)
所以我用这样的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类型
尝试将类强制转换为抽象命令时
AbstractCommand command = (AbstractCommand) commandClass.getClass().newInstance();
它告诉我类不能转换为AbstractCommand
所以我想知道我做错了什么
再次感谢您提供的任何帮助
# 1 楼答案
我想你想要什么而不是什么
是
commandClass本身就是一个类。因此,对其调用getClass()将返回java。类,并且如果您要实例化它(您不能,但如果可以),它将不可分配给AbstractCommand。但是除去额外的getClass(),您就拥有了命令的类,当您实例化它时,您将得到一个AbstractCommand实例。我想其他一切都很好