How does @EventHandler work?

Discussion in 'Plugin Development' started by Parky, Feb 18, 2019.

Thread Status:
Not open for further replies.
  1. Offline

    Parky

    When I put @EventHandler in any method, this method is executed in case some event occurs.

    How is this possible? How does it run and put information in the method parameter? I've heard that it invokes all annotations, but can you illustrate this in a few lines of code?

    This is interesting because some people say it's magic.
     
  2. Online

    timtower Administrator Administrator Moderator

    @Parky It is magic, as far as I am aware it is done using with reflection (which can be a nasty thing).
    When you register a class it gets checked, every method with @EventHandler gets added to a list per event type.
    Then when the event occurs the server runs all methods.
     
  3. Offline

    Parky

    @timtower Stirring with reflection is complicated, you have to drink a lot of coffee. I did not know that I used reflection
     
  4. Online

    timtower Administrator Administrator Moderator

    Reflection can be nasty, but also quite useful, not safe though if misused (which I tend to do :p)
     
  5. Offline

    Parky

    I will delve deeper into this, to program in the reflection. :D
     
  6. Online

    timtower Administrator Administrator Moderator

    If you need it within your own plugins then you are doing something wrong.
    I use it for dynamic class choosing (too lazy to make big if statement)
    Normally you shouldn't need it.
     
  7. Offline

    Parky

    Ok

    It's just out of curiosity, whenever I create my plugins with the event, I have to use EventHandler. Because I do not understand that.
     
    Last edited: Feb 18, 2019
  8. Online

    timtower Administrator Administrator Moderator

    @Parky It is to let Bukkit know that it should be handled as an event.
    Using all methods with events is also possible but that is not always wanted behaviour.
     
    Parky likes this.
  9. Offline

    Tabuu_

    The @EventHandler is an annotation to mark methods as being event handler methods. It is used to 'register' a method so it will be called when the event is fired.
     
Thread Status:
Not open for further replies.

Share This Page