Skip to content

Factory annotation

Jonathan edited this page Jan 10, 2018 · 5 revisions

Factory annotation is used to generate a stub factory interface at compile-time (with annotation processor) to be implemented at runtime with a factory code that create events instances.

Since EventSys recommends usage of interfaces to specify events rather than concrete classes, the creation of an instance of an event specified by an interface requires some code to be written. To avoid this, we introduced Factory interfaces feature:

interface MyFactory {
   fun createBuyEvent(@Name("product") product: Product, @Name("amount") amount: Int): BuyEvent
}

This makes the process of creating new instances of events more easy and simple, you only need to use EventGenerator.createFactory to create instance of the factory, and then use it.

But if you have too much events, writting this stub interface can be tedious and even slow down the development, so @Factory was introduced.

Every event annotation that you wish to have a factory method in a factory interface should be annotated with @Factory. The value property is the name of target interface to add the factory method (the target interface cannot exists, Annotation Processor will create it).

Example:

@Factory("com.github.projectsandstone.eventsyswiki.MyFactory")
interface BuyEvent : Event {
    val product: Product
    val amount: Int
}

This will generate a factory stub interface when you compile. The implementation still need to be generated at runtime with EventGenerator.createFactory, but now you don't need to write an interface method for every event.

@Factories

Container annotation to be used to specify multiple factories with @Factory, this is commonly used to generate variants with extensions.

Final note

These examples uses Kotlin language, to this work you need to configure Kotlin KAPT with EventSys as a kapt annotation processor.

Also, to be able to use generated classes, you should add the generated class directory to project source set:

sourceSets {
    main {
        java {
            srcDirs "build/generated/source/kapt/main"
        }
    }
}

In this example, we used Kapt to generate sources, so we added kapt generated directory, but for Java you need to add another directory (corresponding directory where java compiler stores the source).