Skip to content

Instantly share code, notes, and snippets.

@LindsayBradford
Created May 1, 2012 12:38
Show Gist options
  • Save LindsayBradford/2567708 to your computer and use it in GitHub Desktop.
Save LindsayBradford/2567708 to your computer and use it in GitHub Desktop.
Doing strict MVC checks that View and Control components of a Model truly are valid Viewers for updates, and Controlers for state changes within Java.
/* public interfaces for controller and view components to implement for a model */
public interface StrictModelViewer extends Observer {};
public interface StrictModelComtroller;
public class StrictModel extends Observable {
/* All model changing calls must come from classes implementing StrictModelController */
public void alterModelState() {
assert ReflectionUtilities.callerImplements(StrictModelController.class);
this.setChagned();
this.notifyObservers();
}
/* Only implementers of StrictModelViewere can become observers */
public void addObserver(Observer observer) {
assert (ReflectionUtilities.classImplements(observer.getClass(), StrictModelViewer.class)) :
"observer specified does not implement the interface StrictModelViewer";
super.addObserver(observer);
}
}
final class ReflectionUtilities {
/**
* Checks to see if the method calling whatever method that invokes
* <tt>callerImplements</tt> implements the supplied interface.
* @param theInterface
* @return
*/
public static boolean callerImplements(Class<?> theInterface) {
StackTraceElement[] elements = new Throwable().getStackTrace();
String callerClassName = elements[2].getClassName();
Class<?> callerClass = null;
try {
callerClass = Class.forName(callerClassName);
} catch (Exception e) {
return false;
}
return classImplements(callerClass, theInterface);
}
/**
* Checks to see if the supplied class implements the supplied interface.
* @param theClass
* @param theInterface
* @return
*/
public static boolean classImplements(Class<?> theClass, Class<?> theInterface) {
Class[] interfaceArray = theClass.getInterfaces();
for (Class<?> thisInterface : interfaceArray) {
if (thisInterface.equals(theInterface)) {
return true;
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment