首先,我必须说我是真正的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();
是给我一个错误(illegalAccessException和InstantiationException)在我的IDE(而不是在编译的时候,因为我还没有尝试它呢)
所以我围绕它与这样的尝试/赶上
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类型。
当试图投类到AbstractCommand做
AbstractCommand command = (AbstractCommand) commandClass.getClass().newInstance();
它告诉我,类不能被转换为AbstractCommand。
所以我想知道我在做什么错?
再次感谢您提供的任何帮助。
getClass()方法获取实际的子类吗? 正在做commandClass.newInstance()试图调用抽象类的构造函数而不是子类? THX您的帮助反正,我来试试这个 – nolazybits
'commandClass.newInstance()'将调用哪个类“commandClass”是默认的构造函数。即如果'commandClass = FooCommand.class',那么'commandClass.newInstance()'与'new FooCommand()'完全相同。合理? –
所以,是的,它不会抱怨了... THX这个......如果你也能回答上述问题的意见;) THX再次大量... – nolazybits