【发布时间】:2015-01-30 23:13:48
【问题描述】:
有一个 Message 超类和各种 Message 子类,如 WeddingMessage、GreetingMessage、FarewellMessage、Birthday Message。
Message 超类有一个构造函数:
public Message(String messageType){
this.messageType = messageType;
}
消息子类都有不同的构造函数,但是它们都调用超类,并在其中将 messageType 作为参数传递 例如:
public BirthdayMessage( String name, int age){
super("birthday");
System.out.println("Happy birthday " + name + "You are " + age " years old");
public FareWellMessage(String name, String message){
super("farewell");
System.out.println(message + " " + name);
}
创建的消息类型由用户传入的参数决定。例如,如果用户插入“birthday John 12”,那么将使用参数 John 和 12 创建 BirthdayMessage。如果用户输入“Farewell Grace take care”,则使用这些参数创建 FarewellMessage 的实例。
而不是一堆 if/else 语句或 switch case,以类似的形式 -
words[] = userinput.slice(' ');
word1 = words[0];
if (word1 == birthday)
create new BirthdayMessage(parameters here)
if (word1 == wedding)
create new weddingMessage(parameters here)
等
我如何使用反射来确定要创建哪种类型的 Message 类。 我目前的想法是使用 File 类来获取包中包含消息子类的所有文件。然后使用反射来获取它们的每个构造函数参数类型,并查看它们是否与用户输入给出的参数匹配。然后用随机参数创建那些匹配类的实例。完成后,子类将使用其 messageType 调用其超类构造函数。然后我可以检查 messageType 变量是否与用户输入匹配。
所以如果用户输入“生日约翰 23” 我发现包中的所有构造函数都将 String 和 int 作为参数并具有字段 messageType(继承自 Message)。然后我创建该类的一个实例并检查 messageType 是否 == 到用户输入中的第一个单词(在本例中为生日)。如果是,那么我使用用户提供的参数创建该类的实例。
有没有更好的方法通过反射来做到这一点?
【问题讨论】:
-
它会比 if/else 或 switch 语句更复杂。
-
每个消息类型构造函数的
parameters here会不同吗? -
@JoseMartinez,我相信是的。 OP 在问题中显示了 2 个似乎不同的示例(BirthdayMessage 和 FarewellMessage)。
-
如果参数不同,问题就会变得更难解决。 if else 语句没有任何问题,只要它们被很好地封装在工厂类中。
-
如果消息空间有限,您可以使用 Enum,但我同意 @Pshemo 的观点,您可能应该只使用不同的格式字符串,而不是疯狂上课。
标签: java design-patterns reflection dynamic-class-creation