Skip to content

Instantly share code, notes, and snippets.

@UnquietCode
Last active December 20, 2015 21:09
Show Gist options
  • Save UnquietCode/6195731 to your computer and use it in GitHub Desktop.
Save UnquietCode/6195731 to your computer and use it in GitHub Desktop.
I use this handler class when I want to have dynamically typed, variable length parameters.
registerStudent(student, new HandlerChain<RegistrationStep>()
.on(RegistrationStep.NEW_STUDENT, new FlexibleHandler() {
void handle(NewRegistrant registrant) {
System.out.println(registrant.info());
}
})
.on(RegistrationStep.USER_EXISTS, new FlexibleHandler() {
void handle(NewRegistrant registrant, UserContainer existingUser) {
System.out.println(registrant.info());
System.out.println(existingUser.info());
}
})
);
public class FlexibleHandler {
// add whatever methods you want!
public final void invoke(Object...args) {
for (Method method : this.getClass().getDeclaredMethods()) {
Object[] newArgs = new Object[method.getParameterTypes().length];
System.arraycopy(args, 0, newArgs, 0, newArgs.length);
try {
method.setAccessible(true);
method.invoke(this, newArgs);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e.getCause());
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment