日期:2014-05-20  浏览次数:20773 次

关于command命令模式中的一个小问题
本帖最后由 wzu_xiaomai 于 2012-10-16 15:57:27 编辑

package com.xiaomai.command;

import java.util.HashMap;
import java.util.Map;

public class Invoker {
public Map commands;

public Invoker() {
commands = new HashMap();
}
public void addCommand(String commName,ICommand command){
commands.put(commName, command);
}
public void request(String commName){
ICommand command = (ICommand) commands.get(commName);
System.out.println(command.getClass());//???为什么是相应的类型 command.excute();
}

}


这个是command模式中的invoker类,在client类中运行之后红色部分代码输出的并不是ICommand接口类型而是实现了ICommand接口的类型,这是为什么?我知道结果必定是这样,但是我不明白它的运行机制啊。。。。
------最佳解决方案--------------------
X
------其他解决方案--------------------
> where 
------其他解决方案--------------------
getClass返回的就是该对象的运行时类,还有什么运行机制?

getClass
public final Class<?> getClass()
Returns the runtime class of this Object. The returned Class object is the object that is locked by static synchronized methods of the represented class. 
The actual result type is Class<? extends 
------其他解决方案--------------------
X
------其他解决方案--------------------
 is the erasure of the static type of the expression on which getClass is called. For example, no cast is required in this code fragment:

Number n = 0; 
Class<? extends Number> c = n.getClass(); 


Returns:
The Class object that represents the runtime class of this object.

------其他解决方案--------------------
Object b = new String();
System.out.println(b.getClass());你是想打印Object相关的内容么
------其他解决方案--------------------
getClass就是返回对象所属类的信息,而不是引用所属类
------其他解决方案--------------------
感谢一楼和二楼的回答。明白了。。。