我希望这个标题能够准确地代表我在这里所要求的内容。对于我在这里的作业,我有一个Speakerphone
对象,它是一个单例,还有两个接口,Listener
和Talker
Speakerphone
需要与之通信。
有两个shoutMessage
方法,第二个方法将Class对象作为参数。在这里,我很困惑 - 我不知道" Class对象"在说明中指的是Listener
接口或Speakerphone
对象。根据这里的说明,有人能告诉我这个方法中的代码是否正确吗?
public class Speakerphone extends Object {
private static Speakerphone sSpeaker = null;
private static HashSet<Listener> mListener = new HashSet<Listener>();
private static HashSet<Talker> mTalker = new HashSet<Talker>();
private Speakerphone() {
}
/*
* get
*
* @return the singleton instance of Speakerphone (Speakerphone)
*/
/************************************************
* ASSIGNMENT:
* Implement the get method
/************************************************/
public static Speakerphone get(){
if (sSpeaker == null){
sSpeaker = new Speakerphone();
}
return sSpeaker;
}
/*
* shoutMessage
*
* Sends the message to all of the Listeners tracked by Speakerphone
*
* @param talker a Talker whose message will be sent (Talker)
* @return nothing
*/
/************************************************
* ASSIGNMENT:
* Implement the shoutMessage method
/************************************************/
public void shoutMessage(Talker talker){
Iterator<Talker> talkIterator = mTalker.iterator();
while(talkIterator.hasNext())
talkIterator.next().getMessage();
}
/*
* shoutMessage
*
* Sends the message to all of the Listeners which are instances of
* the cls parameter
*
* @param talker a Talker whose message will be sent (Talker)
* @param cls a Class object representing the type which the Listener
* should extend from in order to receive the message (Class)
* @return nothing
*
* HINT: see Class.isAssignableFrom()
* http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#isAssignableFrom(java.lang.Class)
*/
/************************************************
* ASSIGNMENT:
* Implement the shoutMessage method
/************************************************/
public void shoutMessage(Talker talker, Class<?> cls){
if (Listener.class.isAssignableFrom(cls)){
Iterator<Talker> talkIterator = mTalker.iterator();
while(talkIterator.hasNext())
talkIterator.next().getMessage();
}
}
}
答案 0 :(得分:0)
因此,shoutMessage
方法中的类参数似乎存在,因此您只能选择某种类型的侦听器。 Java中的Class
是一个描述数据类型的对象 - 可以这么说的meta元。
根据代码中的注释,您的shoutMessage
方法看起来可能与您想要的相反。以下是我认为需要做的事情(根据方法的评论):
Listener.class.isAssignableFrom
确定当前侦听器是否属于cls
类。cls
,则调用talker.getMessage()
并将该消息传递给当前的侦听器(通过调用&#34; receiveMessage&#34;或&#34; on&#34;或者您在Listener界面中定义的任何函数。)cls
类型,则忽略。