Пример #1
1
  protected PsmMethodAction(Class c, String m, Class[] argArray) {
    // This prevents IllegalAccessExceptions when attempting to
    // invoke methods on a class that is in another package and not
    // defined 'public'.
    if (!Modifier.isPublic(c.getModifiers())) {
      throw new IllegalPsmMethodActionException("Action class must be public.");
    }

    try {
      method = c.getMethod(m, argArray);
    } catch (NoSuchMethodException ex) {
      throw new IllegalPsmMethodActionException(ex.toString() + ": method " + m);
    }

    // Check each exception this method declares thrown.  If it declares
    // exceptions, and any of them are not runtime exceptions, abort.
    Class[] exceptionTypes = method.getExceptionTypes();
    for (int i = 0; i < exceptionTypes.length; i++) {
      Class exceptionClass = exceptionTypes[i];
      if (!RuntimeException.class.isAssignableFrom(exceptionClass)) {
        throw new IllegalPsmMethodActionException(
            "Method must not declare non-Runtime " + "exceptions.");
      }
    }

    // Ensure that the method returns PsmEvent
    if (PsmEvent.class != method.getReturnType()) {
      throw new IllegalPsmMethodActionException("Method return type must be PsmEvent");
    }

    // Ensure that both the method is both public and static.
    if (!Modifier.isStatic(method.getModifiers()) || !Modifier.isPublic(method.getModifiers())) {
      throw new IllegalPsmMethodActionException("Method " + m + " must be static and public.");
    }
  }
Пример #2
0
  private void validateClass(Class<?> source, ValidationProblemCollector problems) {
    int modifiers = source.getModifiers();

    if (Modifier.isInterface(modifiers)) {
      problems.add("Must be a class, not an interface");
    }

    if (source.getEnclosingClass() != null) {
      if (Modifier.isStatic(modifiers)) {
        if (Modifier.isPrivate(modifiers)) {
          problems.add("Class cannot be private");
        }
      } else {
        problems.add("Enclosed classes must be static and non private");
      }
    }

    Constructor<?>[] constructors = source.getDeclaredConstructors();
    for (Constructor<?> constructor : constructors) {
      if (constructor.getParameterTypes().length > 0) {
        problems.add("Cannot declare a constructor that takes arguments");
        break;
      }
    }

    Field[] fields = source.getDeclaredFields();
    for (Field field : fields) {
      int fieldModifiers = field.getModifiers();
      if (!field.isSynthetic()
          && !(Modifier.isStatic(fieldModifiers) && Modifier.isFinal(fieldModifiers))) {
        problems.add(field, "Fields must be static final.");
      }
    }
  }
  /**
   * Calls all public methods declared in the class corresponding to the given object. Does not
   * include methods from superclasses.
   *
   * @param object object to call the public methods on
   * @param comparator method comparator, allows running the methods in a specific order
   * @return list of methods invoked, including the parameters used for calling them
   */
  private static List<MethodInvocation> callPublicMethodsInOrder(
      Object object, Comparator<Method> comparator) {
    try {
      List<MethodInvocation> invocations = new ArrayList<>();
      Method[] methods = object.getClass().getDeclaredMethods();
      if (comparator != null) Arrays.sort(methods, comparator);

      for (Method method : methods) {
        if (Modifier.isStatic(method.getModifiers()) || !Modifier.isPublic(method.getModifiers()))
          continue;

        Object[] params = new Object[method.getParameterTypes().length];
        for (int i = 0; i < method.getParameterTypes().length; i++) {
          params[i] = instantiateType(method.getParameterTypes()[i]);
        }
        method.invoke(object, params);
        invocations.add(new MethodInvocation(method.getName(), params));
      }
      return invocations;
    } catch (Exception ex) {
      ex.printStackTrace();
      assertTrue(
          "Error calling public methods on object "
              + object
              + " ("
              + object.getClass().getSimpleName()
              + ")",
          false);
      return new ArrayList<>();
    }
  }
Пример #4
0
 static Method[] getOverridableMethods(Class c) {
   ArrayList<Method> list = new ArrayList<Method>();
   HashSet<String> skip = new HashSet<String>();
   while (c != null) {
     Method[] methods = c.getDeclaredMethods();
     for (int i = 0; i < methods.length; i++) {
       String methodKey =
           methods[i].getName() + getMethodSignature(methods[i], methods[i].getParameterTypes());
       if (skip.contains(methodKey)) continue; // skip this method
       int mods = methods[i].getModifiers();
       if (Modifier.isStatic(mods)) continue;
       if (Modifier.isFinal(mods)) {
         // Make sure we don't add a final method to the list
         // of overridable methods.
         skip.add(methodKey);
         continue;
       }
       if (Modifier.isPublic(mods) || Modifier.isProtected(mods)) {
         list.add(methods[i]);
         skip.add(methodKey);
       }
     }
     c = c.getSuperclass();
   }
   return list.toArray(new Method[list.size()]);
 }
Пример #5
0
 private void validateNonRuleMethod(Method method, ValidationProblemCollector problems) {
   if (!Modifier.isPrivate(method.getModifiers())
       && !Modifier.isStatic(method.getModifiers())
       && !method.isSynthetic()
       && !ModelSchemaUtils.isObjectMethod(method)) {
     problems.add(method, "A method that is not annotated as a rule must be private");
   }
 }
Пример #6
0
  private void validateRuleMethod(
      MethodRuleDefinition<?, ?> ruleDefinition,
      Method ruleMethod,
      ValidationProblemCollector problems) {
    if (Modifier.isPrivate(ruleMethod.getModifiers())) {
      problems.add(ruleMethod, "A rule method cannot be private");
    }
    if (Modifier.isAbstract(ruleMethod.getModifiers())) {
      problems.add(ruleMethod, "A rule method cannot be abstract");
    }

    if (ruleMethod.getTypeParameters().length > 0) {
      problems.add(ruleMethod, "Cannot have type variables (i.e. cannot be a generic method)");
    }

    // TODO validations on method: synthetic, bridge methods, varargs, abstract, native
    ModelType<?> returnType = ModelType.returnType(ruleMethod);
    if (returnType.isRawClassOfParameterizedType()) {
      problems.add(
          ruleMethod,
          "Raw type "
              + returnType
              + " used for return type (all type parameters must be specified of parameterized type)");
    }

    for (int i = 0; i < ruleDefinition.getReferences().size(); i++) {
      ModelReference<?> reference = ruleDefinition.getReferences().get(i);
      if (reference.getType().isRawClassOfParameterizedType()) {
        problems.add(
            ruleMethod,
            "Raw type "
                + reference.getType()
                + " used for parameter "
                + (i + 1)
                + " (all type parameters must be specified of parameterized type)");
      }
      if (reference.getPath() != null) {
        try {
          ModelPath.validatePath(reference.getPath().toString());
        } catch (Exception e) {
          problems.add(
              ruleDefinition,
              "The declared model element path '"
                  + reference.getPath()
                  + "' used for parameter "
                  + (i + 1)
                  + " is not a valid path",
              e);
        }
      }
    }
  }
Пример #7
0
 static Method[] getOverridableMethods(Class c) {
   ArrayList list = new ArrayList();
   while (c != null) {
     Method[] methods = c.getDeclaredMethods();
     for (int i = 0; i < methods.length; i++) {
       int mods = methods[i].getModifiers();
       if (Modifier.isStatic(mods) || Modifier.isFinal(mods)) continue;
       if (Modifier.isPublic(mods) || Modifier.isProtected(mods)) list.add(methods[i]);
     }
     c = c.getSuperclass();
   }
   return (Method[]) list.toArray(new Method[list.size()]);
 }
Пример #8
0
 private boolean _isIncludableField(Field f) {
   /* I'm pretty sure synthetic fields are to be skipped...
    * (methods definitely are)
    */
   if (f.isSynthetic()) {
     return false;
   }
   // Static fields are never included, nor transient
   int mods = f.getModifiers();
   if (Modifier.isStatic(mods) || Modifier.isTransient(mods)) {
     return false;
   }
   return true;
 }
 /**
  * Registers method if it: a. is public, and b. is named "convertXxx", and c. has a return type of
  * "RexNode" or a subtype d. has a 2 parameters with types ConvertletContext and SqlNode (or a
  * subtype) respectively.
  */
 private void registerNodeTypeMethod(final Method method) {
   if (!Modifier.isPublic(method.getModifiers())) {
     return;
   }
   if (!method.getName().startsWith("convert")) {
     return;
   }
   if (!RexNode.class.isAssignableFrom(method.getReturnType())) {
     return;
   }
   final Class[] parameterTypes = method.getParameterTypes();
   if (parameterTypes.length != 2) {
     return;
   }
   if (parameterTypes[0] != SqlRexContext.class) {
     return;
   }
   final Class parameterType = parameterTypes[1];
   if (!SqlNode.class.isAssignableFrom(parameterType)) {
     return;
   }
   map.put(
       parameterType,
       new SqlRexConvertlet() {
         public RexNode convertCall(SqlRexContext cx, SqlCall call) {
           try {
             return (RexNode) method.invoke(ReflectiveConvertletTable.this, cx, call);
           } catch (IllegalAccessException e) {
             throw Util.newInternal(e, "while converting " + call);
           } catch (InvocationTargetException e) {
             throw Util.newInternal(e, "while converting " + call);
           }
         }
       });
 }
Пример #10
0
  public static String isLocalType(Class<?> type) {
    /* As per [JACKSON-187], GAE seems to throw SecurityExceptions
     * here and there... and GAE itself has a bug, too
     * (see []). Bah.
     */
    try {
      // one more: method locals, anonymous, are not good:
      if (type.getEnclosingMethod() != null) {
        return "local/anonymous";
      }

      /* But how about non-static inner classes? Can't construct
       * easily (theoretically, we could try to check if parent
       * happens to be enclosing... but that gets convoluted)
       */
      if (type.getEnclosingClass() != null) {
        if (!Modifier.isStatic(type.getModifiers())) {
          return "non-static member class";
        }
      }
    } catch (SecurityException e) {
    } catch (NullPointerException e) {
    }
    return null;
  }
Пример #11
0
 public static <T> Constructor<T> findConstructor(Class<T> cls, boolean canFixAccess)
     throws IllegalArgumentException {
   try {
     Constructor<T> ctor = cls.getDeclaredConstructor();
     if (canFixAccess) {
       checkAndFixAccess(ctor);
     } else {
       // Has to be public...
       if (!Modifier.isPublic(ctor.getModifiers())) {
         throw new IllegalArgumentException(
             "Default constructor for "
                 + cls.getName()
                 + " is not accessible (non-public?): not allowed to try modify access via Reflection: can not instantiate type");
       }
     }
     return ctor;
   } catch (NoSuchMethodException e) {;
   } catch (Exception e) {
     ClassUtil.unwrapAndThrowAsIAE(
         e,
         "Failed to find default constructor of class "
             + cls.getName()
             + ", problem: "
             + e.getMessage());
   }
   return null;
 }
Пример #12
0
  /**
   * Given an abstract dispatch to an object of type c and a method m, gives a list of possible
   * receiver methods.
   */
  public List resolveAbstractDispatch(SootClass c, SootMethod m) {
    c.checkLevel(SootClass.HIERARCHY);
    m.getDeclaringClass().checkLevel(SootClass.HIERARCHY);
    checkState();

    Iterator<SootClass> classesIt = null;

    if (c.isInterface()) {
      classesIt = getImplementersOf(c).iterator();
      HashSet<SootClass> classes = new HashSet<SootClass>();
      while (classesIt.hasNext()) classes.addAll(getSubclassesOfIncluding(classesIt.next()));
      classesIt = classes.iterator();
    } else classesIt = getSubclassesOfIncluding(c).iterator();

    ArraySet s = new ArraySet();

    while (classesIt.hasNext()) {
      SootClass cl = classesIt.next();
      if (Modifier.isAbstract(cl.getModifiers())) continue;
      s.add(resolveConcreteDispatch(cl, m));
    }

    List l = new ArrayList();
    l.addAll(s);
    return Collections.unmodifiableList(l);
  }
 public void generate(JNIField field) {
   String name = field.getName();
   Iterator<File> keys = files.keySet().iterator();
   while (keys.hasNext()) {
     File key = keys.next();
     String str = files.get(key);
     if (str.indexOf(name) != -1) {
       int modifiers = field.getModifiers();
       String modifiersStr = Modifier.toString(modifiers);
       output("\t");
       output(modifiersStr);
       if (modifiersStr.length() > 0) output(" ");
       output(field.getType().getTypeSignature3(false));
       output(" ");
       output(field.getName());
       output(" = ");
       output(getFieldValue(field));
       outputln(";");
       usedCount++;
       return;
     }
   }
   unusedCount++;
   // output("NOT USED=" + field.toString() + " \n");
 }
Пример #14
0
  protected void _addFactoryMixIns(Class<?> mixin) {
    MemberKey[] methodKeys = null;
    int methodCount = _creatorMethods.size();

    for (Method m : mixin.getDeclaredMethods()) {
      if (!Modifier.isStatic(m.getModifiers())) {
        continue;
      }
      if (m.getParameterTypes().length == 0) {
        continue;
      }
      if (methodKeys == null) {
        methodKeys = new MemberKey[methodCount];
        for (int i = 0; i < methodCount; ++i) {
          methodKeys[i] = new MemberKey(_creatorMethods.get(i).getAnnotated());
        }
      }
      MemberKey key = new MemberKey(m);
      for (int i = 0; i < methodCount; ++i) {
        if (!key.equals(methodKeys[i])) {
          continue;
        }
        _addMixOvers(m, _creatorMethods.get(i), true);
        break;
      }
    }
  }
Пример #15
0
  public JavaType findType(String name) {
    if (_bindings == null) {
      _resolve();
    }
    JavaType t = _bindings.get(name);
    if (t != null) {
      return t;
    }
    if (_placeholders != null && _placeholders.contains(name)) {
      return UNBOUND;
    }
    // New with 1.7: check parent context
    if (_parentBindings != null) {
      return _parentBindings.findType(name);
    }
    // nothing found, so...
    // Should we throw an exception or just return null?

    /* [JACKSON-499] 18-Feb-2011, tatu: There are some tricky type bindings within
     *   java.util, such as HashMap$KeySet; so let's punt the problem
     *   (honestly not sure what to do -- they are unbound for good, I think)
     */
    if (_contextClass != null) {
      Class<?> enclosing = _contextClass.getEnclosingClass();
      if (enclosing != null) {
        // [JACKSON-572]: Actually, let's skip this for all non-static inner classes
        //   (which will also cover 'java.util' type cases...
        if (!Modifier.isStatic(_contextClass.getModifiers())) {
          return UNBOUND;
        }

        // ... so this piece of code should not be needed any more
        /*
        Package pkg = enclosing.getPackage();
        if (pkg != null) {
            // as per [JACKSON-533], also include "java.util.concurrent":
            if (pkg.getName().startsWith("java.util")) {
                return UNBOUND;
            }
        }
        */
      }
    }

    String className;
    if (_contextClass != null) {
      className = _contextClass.getName();
    } else if (_contextType != null) {
      className = _contextType.toString();
    } else {
      className = "UNKNOWN";
    }
    throw new IllegalArgumentException(
        "Type variable '"
            + name
            + "' can not be resolved (with context of class "
            + className
            + ")");
    // t = UNBOUND;
  }
Пример #16
0
  public static void main(String[] args) {
    // read class name from command line args or user input
    String name;
    if (args.length > 0) name = args[0];
    else {
      Scanner in = new Scanner(System.in);
      System.out.println("Enter class name (e.g. java.util.Date): ");
      name = in.next();
    }

    try {
      // print class name and superclass name (if != Object)
      Class cl = Class.forName(name);
      Class supercl = cl.getSuperclass();
      String modifiers = Modifier.toString(cl.getModifiers());
      if (modifiers.length() > 0) System.out.print(modifiers + " ");
      System.out.print("class " + name);
      if (supercl != null && supercl != Object.class)
        System.out.print(" extends " + supercl.getName());

      System.out.print("\n{\n");
      printConstructors(cl);
      System.out.println();
      printMethods(cl);
      System.out.println();
      printFields(cl);
      System.out.println("}");
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
    System.exit(0);
  }
Пример #17
0
 /**
  * Gets the ObjectLoader for the specified class.
  *
  * @param classtype the class
  * @return the ObjectLoader
  */
 public static XML.ObjectLoader getLoader(Class classtype) {
   // look for registered loader first
   ObjectLoader loader = (ObjectLoader) loaders.get(classtype);
   // if no registered loader, look for static getLoader() method in class
   if (loader == null) {
     try {
       Method method = classtype.getMethod("getLoader", (Class[]) null); // $NON-NLS-1$
       if (method != null && Modifier.isStatic(method.getModifiers())) {
         loader = (ObjectLoader) method.invoke(null, (Object[]) null);
         if (loader != null) {
           // register loader for future calls
           setLoader(classtype, loader);
         }
       }
     } catch (Exception ex) {
       /** empty block */
     }
   }
   // if still no loader found, use the default loader
   if (loader == null) {
     if (defaultLoader == null) {
       defaultLoader = new XMLLoader();
     }
     loader = defaultLoader;
   }
   return loader;
 }
Пример #18
0
 {
   for (Method m : this.getClass().getDeclaredMethods()) {
     if (m.getName().matches("m[0-9]+(_check)?")) {
       assert (Modifier.isStatic(m.getModifiers())) : m;
       tests.put(m.getName(), m);
     }
   }
 }
Пример #19
0
  private <T> CachedRuleSource doExtract(final Class<T> source) {
    final ModelType<T> type = ModelType.of(source);
    DefaultMethodModelRuleExtractionContext context =
        new DefaultMethodModelRuleExtractionContext(type, this);

    // TODO - exceptions thrown here should point to some extensive documentation on the concept of
    // class rule sources

    StructSchema<T> schema = getSchema(source, context);
    if (schema == null) {
      throw new InvalidModelRuleDeclarationException(context.problems.format());
    }

    // sort for determinism
    Set<Method> methods = new TreeSet<Method>(Ordering.usingToString());
    methods.addAll(Arrays.asList(source.getDeclaredMethods()));

    ImmutableList.Builder<ModelProperty<?>> implicitInputs = ImmutableList.builder();
    ModelProperty<?> target = null;
    for (ModelProperty<?> property : schema.getProperties()) {
      if (property.isAnnotationPresent(RuleTarget.class)) {
        target = property;
      } else if (property.isAnnotationPresent(RuleInput.class)
          && !(property.getSchema() instanceof ScalarValueSchema)) {
        implicitInputs.add(property);
      }
      for (WeaklyTypeReferencingMethod<?, ?> method : property.getAccessors()) {
        methods.remove(method.getMethod());
      }
    }

    ImmutableList.Builder<ExtractedRuleDetails> rules = ImmutableList.builder();
    for (Method method : methods) {
      MethodRuleDefinition<?, ?> ruleDefinition =
          DefaultMethodRuleDefinition.create(source, method);
      ExtractedModelRule rule = getMethodHandler(ruleDefinition, method, context);
      if (rule != null) {
        rules.add(new ExtractedRuleDetails(ruleDefinition, rule));
      }
    }

    if (context.hasProblems()) {
      throw new InvalidModelRuleDeclarationException(context.problems.format());
    }

    StructBindings<T> bindings = structBindingsStore.getBindings(schema);

    if (schema.getProperties().isEmpty()) {
      return new StatelessRuleSource(
          rules.build(),
          Modifier.isAbstract(source.getModifiers())
              ? new AbstractRuleSourceFactory<T>(schema, bindings, proxyFactory)
              : new ConcreteRuleSourceFactory<T>(type));
    } else {
      return new ParameterizedRuleSource(
          rules.build(), target, implicitInputs.build(), schema, bindings, proxyFactory);
    }
  }
Пример #20
0
  /**
   * Checks that a callback method is present and correctly defined.
   *
   * <p>Having checked it, you can call it using callback().
   *
   * @param sCallback Name of callback method
   * @throws OmDeveloperException If the method doesn't exist or is defined incorrectly
   */
  public void checkCallback(String sCallback) throws OmDeveloperException {
    try {
      Method m = getClass().getMethod(sCallback, new Class[0]);

      if (m.getReturnType() != void.class)
        throw new OmDeveloperException("Callback method " + sCallback + "() must return void");
      if (!Modifier.isPublic(m.getModifiers()))
        throw new OmDeveloperException("Callback method " + sCallback + "() must be public");
      if (Modifier.isStatic(m.getModifiers()))
        throw new OmDeveloperException("Callback method " + sCallback + "() may not be static");
      if (Modifier.isAbstract(m.getModifiers()))
        throw new OmDeveloperException("Callback method " + sCallback + "() may not be abstract");

      sCheckedCallbacks.add(sCallback);
    } catch (NoSuchMethodException e) {
      throw new OmDeveloperException("Callback method " + sCallback + "() does not exist");
    }
  }
Пример #21
0
  private MutableTreeNode populateAttributes(CavityDBObject obj) {
    DefaultMutableTreeNode tree = new DefaultMutableTreeNode("attrs");
    Class cls = obj.getClass();
    for (Field f : cls.getFields()) {
      int mod = f.getModifiers();
      if (Modifier.isPublic(mod) && !Modifier.isStatic(mod)) {
        String fieldName = f.getName();
        try {
          Object value = f.get(obj);
          tree.add(
              new DefaultMutableTreeNode(String.format("%s=%s", fieldName, String.valueOf(value))));

        } catch (IllegalAccessException e) {
          // do nothing.
        }
      }
    }
    return tree;
  }
Пример #22
0
 public void process(File cFile) {
   try {
     String cName = ClassNameFinder.thisClass(BinaryFile.read(cFile));
     if (!cName.contains("")) return; // Ignore unpackaged classes
     testClass = Class.forName(cName);
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
   TestMethods testMethods = new TestMethods();
   Method creator = null;
   Method cleanup = null;
   for (Method m : testClass.getDeclaredMethods()) {
     testMethods.addIfTestMethod(m);
     if (creator == null) creator = checkForCreatorMethod(m);
     if (cleanup == null) cleanup = checkForCleanupMethod(m);
   }
   if (testMethods.size() > 0) {
     if (creator == null)
       try {
         if (!Modifier.isPublic(testClass.getDeclaredConstructor().getModifiers())) {
           Print.print("Error: " + testClass + " default constructor must be public");
           System.exit(1);
         }
       } catch (NoSuchMethodException e) {
         // Synthesized default constructor; OK
       }
     Print.print(testClass.getName());
   }
   for (Method m : testMethods) {
     Print.printnb("  . " + m.getName() + " ");
     try {
       Object testObject = createTestObject(creator);
       boolean success = false;
       try {
         if (m.getReturnType().equals(boolean.class)) success = (Boolean) m.invoke(testObject);
         else {
           m.invoke(testObject);
           success = true; // If no assert fails
         }
       } catch (InvocationTargetException e) {
         // Actual exception is inside e:
         Print.print(e.getCause());
       }
       Print.print(success ? "" : "(failed)");
       testsRun++;
       if (!success) {
         failures++;
         failedTests.add(testClass.getName() + ": " + m.getName());
       }
       if (cleanup != null) cleanup.invoke(testObject, testObject);
     } catch (Exception e) {
       throw new RuntimeException(e);
     }
   }
 }
Пример #23
0
 /**
  * attempt to invoke a Method with the given Object arguments, performing static method
  * auto-detection and automatic array compression
  */
 public static Object invokeMethod(Method m, Object[] o)
     throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
   Object obj;
   Object[] args;
   Class[] c = m.getParameterTypes();
   int num = (o == null) ? 0 : o.length;
   int len = -1;
   int a = -1;
   if (c != null) {
     len = c.length;
     for (int i = 0; i < len; i++) {
       if (c[i].isArray()) a = i;
     }
   }
   if (Modifier.isStatic(m.getModifiers())) {
     // static method
     obj = null;
     if (num > 0) {
       if (a < 0) {
         args = new Object[num];
         System.arraycopy(o, 0, args, 0, num);
       } else {
         // compress some of the arguments into array form
         args = new Object[len];
         if (a > 0) System.arraycopy(o, 0, args, 0, a);
         Object array = Array.newInstance(c[a].getComponentType(), num - len + 1);
         System.arraycopy(o, a, array, 0, num - len + 1);
         args[a] = array;
         if (a < len - 1) System.arraycopy(o, num - len + a + 1, args, a + 1, len - a - 1);
       }
     } else args = null;
   } else {
     // object method
     if (num > 0) obj = o[0];
     else {
       // invalid object method
       return null;
     }
     if (num > 1) {
       if (a < 0) {
         args = new Object[num - 1];
         System.arraycopy(o, 1, args, 0, num - 1);
       } else {
         // compress some of the arguments into array form
         args = new Object[len];
         if (a > 0) System.arraycopy(o, 1, args, 0, a);
         Object array = Array.newInstance(c[a].getComponentType(), num - len);
         System.arraycopy(o, a + 1, array, 0, num - len);
         args[a + 1] = array;
         if (a < len - 1) System.arraycopy(o, num - len + a + 1, args, a + 1, len - a - 1);
       }
     } else args = null;
   }
   return m.invoke(obj, args);
 }
Пример #24
0
 private static void appendOverridableMethods(
     Class<?> c, ArrayList<Method> list, HashSet<String> skip) {
   Method[] methods = c.getDeclaredMethods();
   for (int i = 0; i < methods.length; i++) {
     String methodKey =
         methods[i].getName() + getMethodSignature(methods[i], methods[i].getParameterTypes());
     if (skip.contains(methodKey)) continue; // skip this method
     int mods = methods[i].getModifiers();
     if (Modifier.isStatic(mods)) continue;
     if (Modifier.isFinal(mods)) {
       // Make sure we don't add a final method to the list
       // of overridable methods.
       skip.add(methodKey);
       continue;
     }
     if (Modifier.isPublic(mods) || Modifier.isProtected(mods)) {
       list.add(methods[i]);
       skip.add(methodKey);
     }
   }
 }
Пример #25
0
 /**
  * Checks if a class fulfills the JavaBeans contract.
  *
  * @param cls the class to check
  */
 public static void checkJavaBean(Class<?> cls) {
   try {
     Constructor<?> constructor = cls.getDeclaredConstructor();
     int classModifiers = cls.getModifiers();
     if (Modifier.isInterface(classModifiers))
       throw new RuntimeException(cls.getName() + " is an interface");
     if (Modifier.isAbstract(classModifiers))
       throw new RuntimeException(
           cls.getName() + " cannot be instantiated - it is an abstract class");
     int modifiers = constructor.getModifiers();
     if (!Modifier.isPublic(modifiers))
       throw new RuntimeException("No public default constructor in " + cls);
   } catch (NoSuchMethodException e) {
     throw new RuntimeException("No default constructor in class " + cls);
   } catch (SecurityException e) {
     logger.error(
         "I am not allowed to check the class by using reflection, "
             + "so I just can hope the class is alright and go on: ",
         e);
   }
 }
    /**
     * Check that all methods declared in the given interface were called. Does *not* include
     * methods from super interfaces.
     *
     * @return this for fluent api
     */
    public MethodCallTester<MonitoredClass> assertAllInterfaceMethodsCalled() {
      List<MethodInvocation> currentInvocation =
          new ArrayList<>(invocations); // Debugger calling toString can mess with this
      for (Method method : mockClass.getDeclaredMethods()) {
        if (Modifier.isStatic(method.getModifiers()) || !Modifier.isPublic(method.getModifiers()))
          continue;

        boolean called = false;
        for (MethodInvocation invocation : currentInvocation) {
          if (invocation.method.equals(method.getName())) {
            called = true;
            break;
          }
        }

        assertTrue(
            "Method " + mockClass.getSimpleName() + "." + method.getName() + " was not called",
            called);
      }
      return this;
    }
Пример #27
0
  /**
   * Prints all fields of a class
   *
   * @param cl a class
   */
  public static void printFields(Class cl) {
    Field[] fields = cl.getDeclaredFields();

    for (Field f : fields) {
      Class type = f.getType();
      String name = f.getName();
      System.out.print("   ");
      String modifiers = Modifier.toString(f.getModifiers());
      if (modifiers.length() > 0) System.out.print(modifiers + " ");
      System.out.println(type.getName() + " " + name + ";");
    }
  }
Пример #28
0
 private static LinkedHashMap<String, Prop> createProps() {
   Field[] fs = Configuration.class.getDeclaredFields();
   LinkedHashMap<String, Prop> res = new LinkedHashMap<String, Prop>();
   for (Field f : fs)
     if (!Modifier.isStatic(f.getModifiers())) {
       Description annotation = f.getAnnotation(Description.class);
       if (annotation != null) {
         String name = f.getName().replace('_', '.');
         res.put(name, new Prop(name, annotation.value(), f));
       }
     }
   return res;
 }
 private void checkString(T instance) {
   assertThat(
       instance.toString(),
       CoreMatchers.startsWith(
           type.getCanonicalName().substring(type.getPackage().getName().length() + 1) + "{"));
   assertThat(instance.toString(), endsWith("}"));
   Class<?> currentType = type;
   do {
     for (Field field : type.getDeclaredFields()) {
       if (!field.isSynthetic()
           && !Modifier.isStatic(field.getModifiers())
           && !ignoredFields.contains(field.getName())) {
         assertThat(instance.toString(), containsString(field.getName()));
       }
     }
   } while ((currentType = currentType.getSuperclass()) != Object.class);
 }
Пример #30
0
 public static boolean hasGetterSignature(Method m) {
   // First: static methods can't be getters
   if (Modifier.isStatic(m.getModifiers())) {
     return false;
   }
   // Must take no args
   Class<?>[] pts = m.getParameterTypes();
   if (pts != null && pts.length != 0) {
     return false;
   }
   // Can't be a void method
   if (Void.TYPE == m.getReturnType()) {
     return false;
   }
   // Otherwise looks ok:
   return true;
 }