Skip to content

Instantly share code, notes, and snippets.

@syntaxi
Created July 3, 2018 10:31
Show Gist options
  • Save syntaxi/ff8f768cc906bcf7b9576b1f5e87f8c5 to your computer and use it in GitHub Desktop.
Save syntaxi/ff8f768cc906bcf7b9576b1f5e87f8c5 to your computer and use it in GitHub Desktop.
Alternative method for constructing a new instance

In place of:

if (eventClass.equals(ChatButton.class)) {
    newEvent = new ChatButton();
    /* ... */
} else if (eventClass.equals(NUISkinEditorButton.class)) {
    newEvent = new NUISkinEditorButton();
} else {
    logger.error("ERROR!!! Event not Identified: " + originalEvent.toString());
}

You can use:

try {
    return originalEvent.getClass()
            .getConstructor()
            .newInstance();

} catch (NoSuchMethodException
        | IllegalAccessException
        | InvocationTargetException
        | InstantiationException
        exception) {
    logger.error("ERROR!!! Event not Identified: " + originalEvent.toString());
}
return null;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment