View Javadoc
1 package xdoclet.util.predicates; 2 3 import xjavadoc.XProgramElement; 4 import xjavadoc.predicates.ProgramElementPredicate; 5 6 import java.lang.reflect.Method; 7 8 /*** 9 * Predicate that uses reflection to call a no-argument method that returns a boolean. 10 * This is so we don't have to write one Predicate for all the different 11 * <code>isXxx()</code> methods in the XJavaDoc API. 12 * 13 * @author <a href="mailto:aslak.hellesoy at bekk.no">Aslak Hellesøy</a> 14 * @version $Revision: 1.5 $ 15 */ 16 public class ReflectionPredicate extends ProgramElementPredicate { 17 private String _methodName; 18 private boolean _negation; 19 20 /*** 21 * Constructs a new ReflectionPredicate. 22 * 23 * @param methodName the method name to evaluate 24 */ 25 public ReflectionPredicate(String methodName) { 26 setMethodName(methodName); 27 } 28 29 protected boolean evaluate(XProgramElement programElement) { 30 // Find the method. We only support methods with no arguments that return a boolean. 31 Method method = null; 32 33 try { 34 method = programElement.getClass().getMethod(_methodName, null); 35 } catch (Exception e) { 36 throw new IllegalStateException(_methodName + " should be a no-arg method (" + e.getMessage() + ")"); 37 } 38 39 assert method != null : "method is null"; 40 41 Class returnType = method.getReturnType(); 42 43 if (returnType != Boolean.TYPE) { 44 throw new IllegalStateException(_methodName + " should return boolean"); 45 } 46 47 Boolean bool = null; 48 49 try { 50 bool = (Boolean) method.invoke(programElement, null); 51 } catch (Exception e) { 52 e.printStackTrace(); 53 throw new IllegalStateException("Failed to invoke " + _methodName); 54 } 55 56 boolean result = bool.booleanValue(); 57 58 result = _negation ? (!result) : result; 59 60 return result; 61 } 62 63 /*** 64 * Sets the method name. Sets negation if methodName starts with !. 65 * 66 * @param methodName the method name 67 */ 68 public void setMethodName(String methodName) { 69 if (methodName == null) { 70 throw new IllegalArgumentException("methodName cannot be null"); 71 } 72 73 if (methodName.trim().length() == 0) { 74 throw new IllegalArgumentException("methodName cannot be empty"); 75 } 76 77 if (methodName.charAt(0) == '!') { 78 _negation = true; 79 _methodName = methodName.substring(1); 80 } else { 81 _negation = false; 82 _methodName = methodName; 83 } 84 } 85 86 public String toString() { 87 return ( _negation ? "!" : "" ) + _methodName + "()"; 88 } 89 }

This page was automatically generated by Maven