I have Scala a project directory structure that looks like this:
myapp/
src/main/scala/
com/
me/
myapp/
messages/
BaseMessage.scala
FizzMessage.scala
utils
<omitted for brevity>
logging
<omitted for brevity>
driver
<omitted for brevity>
Notice the messages
package. Currently it only has two classes defined inside of it, BaseMessage
(an abstract base class) and FizzMessage
(extends BaseMessage
). But eventually it will contain hundreds of other classes that are all BaseMessage
subclasses.
In my code I have the following:
deviceManager.registerMessage(new FizzMessage())
As I add dozens, possibly hundreds of BaseMessage
subclasses to that messages
package over time, I would have to add a line of code to "register" each new message type. Subsequently, if I refactor or remove messages I will have to remember to remove their respective line of registration code from above. This will be a pain to manage and I'm wondering if I could just use reflection to scan the messages
package for BaseMessage
impls, and then subsequently register them:
val messageImpls : Array[T > BaseMessage] = getViaReflection("com.me.myapp.messages")
messageImpls.foreach { msgImpl =>
deviceManager.registerMessage(msgImpl)
}
Any ideas as to how I could accomplish this?
Aucun commentaire:
Enregistrer un commentaire