import java.lang.reflect.*; import java.util.*; /* An example of an encapsulation checker. It checks that all nonstatic fields of a class * are private and can be accessed by public get methods. */ class EncCheck { StringBuffer errorLog = new StringBuffer(); // Empty if no errors. Class clazz; // the class we are currently checking List nonStaticFields; // null, or a list of all non-static fields // precondition: clazz != null public void findAllNonStaticFields(){ Field[] fields = clazz.getDeclaredFields(); nonStaticFields = new ArrayList(); for (Field f : fields){ int modifiers = f.getModifiers(); if (! Modifier.isStatic(modifiers) ) nonStaticFields.add(f); } } public void ensurePrivate() { for ( Field f : nonStaticFields){ int modifiers = f.getModifiers(); if (! Modifier.isPrivate(modifiers) ) errorLog.append (f.toString() + " is not private\n"); } } private static final Class[] noParameters = new Class[0]; public void ensureGetters(){ for ( Field f : nonStaticFields){ try{ clazz.getMethod(getter(f), noParameters); }catch(NoSuchMethodException ex){ errorLog.append (f.toString() + " has no accessor\n"); } } } private String getter (Field f){ String name = f.getName(); String first = name.substring(0,0).toUpperCase(); String rest = name.substring(1,name.length()); return "get"+ first + rest; } public void check(Class c) throws Exception { clazz = c; findAllNonStaticFields(); ensurePrivate(); ensureGetters(); //… do the check if (errorLog.length() > 0 ) System.out.println(errorLog.toString()); else System.out.println("No errors"); } public static void main(String[] args) throws Exception { String className = args[0]; Class c = Class.forName(className); EncCheck checker = new EncCheck(); checker.check(c); } }