Example #1
0
  private void addClass(Class<?> c) {
    if (classes.add(c)) {
      if (c.getSuperclass() != null) {
        addClass(c.getSuperclass());
      }
      for (Class<?> sc : c.getInterfaces()) {
        addClass(sc);
      }
      for (Class<?> dc : c.getDeclaredClasses()) {
        addClass(dc);
      }
      for (Method m : c.getDeclaredMethods()) {
        addClass(m.getReturnType());
        for (Class<?> p : m.getParameterTypes()) {
          addClass(p);
        }
      }

      if (c != void.class && dimensions(c) < 2) {
        Class<?> arrayClass = Array.newInstance(c, 0).getClass();
        arrayClasses.put(c, arrayClass);
        addClass(arrayClass);
      }
    }
  }
Example #2
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()]);
 }
 protected void _addMethodMixIns(
     MethodFilter methodFilter,
     AnnotatedMethodMap methods,
     Class<?> mixInCls,
     AnnotatedMethodMap mixIns) {
   for (Method m : mixInCls.getDeclaredMethods()) {
     if (!_isIncludableMethod(m, methodFilter)) {
       continue;
     }
     AnnotatedMethod am = methods.find(m);
     /* Do we already have a method to augment (from sub-class
      * that will mask this mixIn)? If so, add if visible
      * without masking (no such annotation)
      */
     if (am != null) {
       _addMixUnders(m, am);
       /* Otherwise will have precedence, but must wait
        * until we find the real method (mixIn methods are
        * just placeholder, can't be called)
        */
     } else {
       mixIns.add(_constructMethod(m));
     }
   }
 }
 private void findBeans() {
   try {
     Object currentConfiguration = null;
     for (Class<?> c : configurations) {
       currentConfiguration = c.newInstance();
       for (Method m : c.getDeclaredMethods()) {
         if (m.isAnnotationPresent(Bean.class)) {
           m.setAccessible(true);
           Class<?> returnClass = m.getReturnType();
           if (m.getAnnotation(Bean.class).value()) {
             beans.put(
                 returnClass.getName(),
                 new SingletonBeanDefinition(returnClass, m.invoke(currentConfiguration)));
           } else {
             beans.put(
                 returnClass.getName(),
                 new PrototypeBeanDefinition(returnClass, currentConfiguration, m));
           }
         }
       }
     }
   } catch (InvocationTargetException | InstantiationException | IllegalAccessException e) {
     e.printStackTrace();
     throw new FailureBeanCreationException(e);
   }
 }
Example #5
0
 /**
  * Handles annotated methods.
  *
  * @param managedClass Used to lookup or create an instance of this class containing the method to
  *     call.
  * @param context The bundle context.
  */
 protected void handleMethods(Class managedClass, BundleContext context) {
   for (Method method : managedClass.getDeclaredMethods()) {
     handleStartupMethods(method, managedClass, context);
     handleShutdownMethods(method, managedClass, context);
     handleListenerMethods(method, managedClass, context);
   }
 }
Example #6
0
  public Method[] getLocalMethodsFromClass(Class c) {

    Method[] mList;

    mList = c.getDeclaredMethods();
    return mList;
  }
  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;
      }
    }
  }
Example #8
0
 /**
  * 返回某类的所有方法集合 key = 大写的方法名 vale = 方法
  *
  * @param aClass class对象
  */
 public static Map<String, Method> getMethodMap(Class aClass) {
   Map methodMap = new HashMap();
   Method[] methods = aClass.getDeclaredMethods();
   for (int i = 0; i < methods.length; i++) {
     methodMap.put(methods[i].getName(), methods[i]);
   }
   return methodMap;
 }
  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);
    }
  }
Example #10
0
 private static Set<String> collectMethodsMetadata(Class<?> testCaseClass) {
   Set<String> filePaths = Sets.newHashSet();
   for (Method method : testCaseClass.getDeclaredMethods()) {
     TestMetadata testMetadata = method.getAnnotation(TestMetadata.class);
     if (testMetadata != null) {
       filePaths.add(testMetadata.value());
     }
   }
   return filePaths;
 }
Example #11
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);
     }
   }
 }
  private Method findPublicVoidMethod(Class<?> aClass, String methodName) {
    for (Method method : aClass.getDeclaredMethods()) {
      if (isPublic(method.getModifiers())
          && method.getReturnType() == void.class
          && methodName.equals(method.getName())) {
        return method;
      }
    }

    return null;
  }
Example #13
0
  private void populateInternalMap(Object bean, boolean includeSuperClass) {
    Class klass = bean.getClass();

    // If klass.getSuperClass is System class then includeSuperClass = false;

    if (klass.getClassLoader() == null) {
      includeSuperClass = false;
    }

    Method[] methods = (includeSuperClass) ? klass.getMethods() : klass.getDeclaredMethods();
    for (int i = 0; i < methods.length; i += 1) {
      try {
        Method method = methods[i];
        String name = method.getName();
        String key = "";
        if (name.startsWith("get")) {
          key = name.substring(3);
        } else if (name.startsWith("is")) {
          key = name.substring(2);
        }
        if (key.length() > 0
            && Character.isUpperCase(key.charAt(0))
            && method.getParameterTypes().length == 0) {
          if (key.length() == 1) {
            key = key.toLowerCase();
          } else if (!Character.isUpperCase(key.charAt(1))) {
            key = key.substring(0, 1).toLowerCase() + key.substring(1);
          }

          Object result = method.invoke(bean, (Object[]) null);
          if (result == null) {
            map.put(key, NULL);
          } else if (result.getClass().isArray()) {
            map.put(key, new JSONArray(result, includeSuperClass));
          } else if (result instanceof Collection) { // List or Set
            map.put(key, new JSONArray((Collection) result, includeSuperClass));
          } else if (result instanceof Map) {
            map.put(key, new JSONObject((Map) result, includeSuperClass));
          } else if (isStandardProperty(result.getClass())) { // Primitives, String and Wrapper
            map.put(key, result);
          } else {
            if (result.getClass().getPackage().getName().startsWith("java")
                || result.getClass().getClassLoader() == null) {
              map.put(key, result.toString());
            } else { // User defined Objects
              map.put(key, new JSONObject(result, includeSuperClass));
            }
          }
        }
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }
  }
  /**
   * Visit every class/interface this proxy should implement, and generate the appropriate bytecode
   * for delegation if available.
   *
   * @param clazz an class for which to generate bytecode
   */
  private void visitClass(final Class clazz) {
    Method[] methods = clazz.getDeclaredMethods();
    for (Method method : methods) {
      Class<?>[] exceptionTypes = method.getExceptionTypes();
      String[] exceptions = new String[exceptionTypes.length];
      for (int i = 0; i < exceptions.length; i++) {
        exceptions[i] = BytecodeHelper.getClassInternalName(exceptionTypes[i]);
      }
      // for each method defined in the class, generate the appropriate delegation bytecode
      visitMethod(
          method.getModifiers(),
          method.getName(),
          BytecodeHelper.getMethodDescriptor(method.getReturnType(), method.getParameterTypes()),
          null,
          exceptions);
    }
    Constructor[] constructors = clazz.getDeclaredConstructors();
    for (Constructor method : constructors) {
      Class<?>[] exceptionTypes = method.getExceptionTypes();
      String[] exceptions = new String[exceptionTypes.length];
      for (int i = 0; i < exceptions.length; i++) {
        exceptions[i] = BytecodeHelper.getClassInternalName(exceptionTypes[i]);
      }
      // for each method defined in the class, generate the appropriate delegation bytecode
      visitMethod(
          method.getModifiers(),
          "<init>",
          BytecodeHelper.getMethodDescriptor(Void.TYPE, method.getParameterTypes()),
          null,
          exceptions);
    }

    for (Class intf : clazz.getInterfaces()) {
      visitClass(intf);
    }
    Class superclass = clazz.getSuperclass();
    if (superclass != null) visitClass(superclass);

    // Ultimately, methods can be available in the closure map which are not defined by the
    // superclass
    // nor the interfaces
    for (Map.Entry<String, Boolean> entry : delegatedClosures.entrySet()) {
      Boolean visited = entry.getValue();
      if (!visited) {
        String name = entry.getKey();
        if (!"*".equals(name)) {
          // generate a new method
          visitMethod(ACC_PUBLIC, name, "([Ljava/lang/Object;)Ljava/lang/Object;", null, null);
        }
      }
    }
  }
  public void processAction(HttpServletRequest request, HttpServletResponse response)
      throws IOException {

    System.out.println("processing test driver request ... ");

    processParams(request);
    boolean status = false;
    System.out.println("tc:" + tc);

    response.setContentType("text/plain");
    ServletOutputStream out = response.getOutputStream();
    out.println("TestCase: " + tc);

    if (tc != null) {

      try {
        Class<?> c = getClass();
        Object t = this;

        Method[] allMethods = c.getDeclaredMethods();
        for (Method m : allMethods) {
          String mname = m.getName();
          if (!mname.equals(tc.trim())) {
            continue;
          }

          System.out.println("Invoking : " + mname);
          try {
            m.setAccessible(true);
            Object o = m.invoke(t);
            System.out.println("Returned => " + (Boolean) o);
            status = new Boolean((Boolean) o).booleanValue();
            // Handle any methods thrown by method to be invoked
          } catch (InvocationTargetException x) {
            Throwable cause = x.getCause();

            System.err.format("invocation of %s failed: %s%n", mname, cause.getMessage());
          } catch (IllegalAccessException x) {
            x.printStackTrace();
          }
        }
      } catch (Exception ex) {
        ex.printStackTrace();
      }

      if (status) {
        out.println(tc + ":pass");
      } else {
        out.println(tc + ":fail");
      }
    }
  }
  /**
   * Configure the default record mapper.
   *
   * @return the default implementation of record mapper
   * @throws BatchConfigurationException if the target type class is not found
   */
  private RecordMapper configureDefaultRecordMapper() throws BatchConfigurationException {

    RecordMapper recordMapper;

    String recordClassName = configurationProperties.getProperty(BatchConstants.INPUT_RECORD_CLASS);
    if (recordClassName == null || recordClassName.length() == 0) {
      try {
        Class recordProcessorClass = Class.forName(recordProcessor.getClass().getName());
        Method[] declaredMethods = recordProcessorClass.getDeclaredMethods();
        for (Method declaredMethod : declaredMethods) {
          if (declaredMethod.getName().equals("processRecord")) {
            recordClassName = declaredMethod.getParameterTypes()[0].getName();
            break;
          }
        }
      } catch (ClassNotFoundException e) {
        String error =
            "Configuration failed : unable to get record class name from registered record processor implementation.";
        logger.severe(error);
        throw new BatchConfigurationException(error, e);
      }
    }

    String[] headers;
    String headersProperty =
        configurationProperties.getProperty(BatchConstants.INPUT_RECORD_HEADERS);
    if (headersProperty
        == null) { // if no headers specified, use field names declared in the header record
      String headerRecord = recordReader.getHeaderRecord();
      Record record =
          recordParser.parseRecord(
              headerRecord,
              0); // use the record parser to parse the header record using the right delimiter
      List<Field> fields = record.getFields();
      headers = new String[fields.size()];
      for (int i = 0; i < fields.size(); i++) {
        headers[i] = fields.get(i).getContent();
      }
    } else { // headers specified, split the comma separated list
      headers = headersProperty.split(",");
    }

    try {
      recordMapper = new DefaultRecordMapperImpl(recordClassName, headers, typeConverters);
    } catch (ClassNotFoundException e) {
      String error = "Configuration failed : Class " + recordClassName + " not found.";
      logger.severe(error);
      throw new BatchConfigurationException(error, e);
    }

    return recordMapper;
  }
Example #17
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()]);
 }
 private static List<Method> getInheritedMethods(Class baseClass, List<Method> methods) {
   Collections.addAll(methods, baseClass.getMethods());
   Class currentClass = baseClass;
   while (currentClass != null) {
     Method[] protectedMethods = currentClass.getDeclaredMethods();
     for (Method method : protectedMethods) {
       if (method.getName().indexOf('$') != -1) continue;
       if (Modifier.isProtected(method.getModifiers())
           && !containsEquivalentMethod(methods, method)) methods.add(method);
     }
     currentClass = currentClass.getSuperclass();
   }
   return methods;
 }
 private void putMethods(AnnotationInfo ai, Class c) {
   Method[] methods = c.getDeclaredMethods();
   for (Method method : methods) {
     //            logger.fine("method=" + method.getName());
     String methodName = method.getName();
     if (!methodName.startsWith("get")) continue;
     //            System.out.println("method=" + methodName);
     if (config.isGroovyBeans()
         && (methodName.equals("getProperty") || methodName.equals("getMetaClass"))) continue;
     Transient transientM = method.getAnnotation(Transient.class);
     if (transientM != null) continue; // we don't save this one
     ai.addGetter(method);
   }
 }
  private static void convertProtocolToAsciidocTable(Properties props, Class<Protocol> clazz)
      throws Exception {
    boolean isUnsupported = clazz.isAnnotationPresent(Unsupported.class);
    if (isUnsupported) return;

    Map<String, String> nameToDescription = new TreeMap<>();

    Field[] fields = clazz.getDeclaredFields();
    for (Field field : fields) {
      if (field.isAnnotationPresent(Property.class)) {
        String property = field.getName();
        Property annotation = field.getAnnotation(Property.class);
        String desc = annotation.description();
        nameToDescription.put(property, desc);
      }
    }

    // iterate methods
    Method[] methods = clazz.getDeclaredMethods();
    for (Method method : methods) {
      if (method.isAnnotationPresent(Property.class)) {

        Property annotation = method.getAnnotation(Property.class);
        String desc = annotation.description();

        if (desc == null || desc.isEmpty()) desc = "n/a";

        String name = annotation.name();
        if (name.length() < 1) {
          name = Util.methodNameToAttributeName(method.getName());
        }
        nameToDescription.put(name, desc);
      }
    }

    // do we have more than one property (superclass Protocol has only one property (stats))
    if (nameToDescription.isEmpty()) return;

    List<String[]> rows = new ArrayList<>(nameToDescription.size() + 1);
    rows.add(new String[] {"Name", "Description"});
    for (Map.Entry<String, String> entry : nameToDescription.entrySet())
      rows.add(new String[] {entry.getKey(), entry.getValue()});

    String tmp =
        createAsciidocTable(
            rows,
            clazz.getSimpleName(),
            "[align=\"left\",width=\"90%\",cols=\"2,10\",options=\"header\"]");
    props.put(clazz.getSimpleName(), tmp);
  }
Example #21
0
 private List<ExcelHeader> getHeaderList(Class clz) {
   List<ExcelHeader> headers = new ArrayList<ExcelHeader>();
   // 获取全部get/is方法
   Method[] ms = clz.getDeclaredMethods();
   for (Method m : ms) {
     String mn = m.getName();
     if (mn.startsWith("get") || mn.startsWith("is")) {
       if (m.isAnnotationPresent(ExcelResources.class)) {
         ExcelResources er = m.getAnnotation(ExcelResources.class);
         headers.add(new ExcelHeader(er.title(), er.order(), mn));
       }
     }
   }
   return headers;
 }
  /**
   * Adds functions from a library class
   *
   * @param library the library class
   */
  public void addLibrary(Class<?> library) {
    for (Method method : library.getDeclaredMethods()) {
      if ((method.getModifiers() & Modifier.PUBLIC) == 0) {
        continue; // ignore non-public methods
      }

      String name = method.getName().toLowerCase();

      // strip preceding _ chars used to avoid conflicts with Java keywords
      if (name.startsWith("_")) {
        name = name.substring(1);
      }

      m_functions.put(name, method);
    }
  }
Example #23
0
  protected void _addMemberMethods(
      Class<?> cls,
      MethodFilter methodFilter,
      AnnotatedMethodMap methods,
      Class<?> mixInCls,
      AnnotatedMethodMap mixIns) {
    // first, mixIns, since they have higher priority then class methods
    if (mixInCls != null) {
      _addMethodMixIns(methodFilter, methods, mixInCls, mixIns);
    }

    if (cls == null) { // just so caller need not check when passing super-class
      return;
    }
    // then methods from the class itself
    for (Method m : cls.getDeclaredMethods()) {
      if (!_isIncludableMethod(m, methodFilter)) {
        continue;
      }
      AnnotatedMethod old = methods.find(m);
      if (old == null) {
        AnnotatedMethod newM = _constructMethod(m);
        methods.add(newM);
        // Ok, but is there a mix-in to connect now?
        old = mixIns.remove(m);
        if (old != null) {
          _addMixOvers(old.getAnnotated(), newM, false);
        }
      } else {
        /* If sub-class already has the method, we only want to augment
         * annotations with entries that are not masked by sub-class.
         */
        _addMixUnders(m, old);

        /* 06-Jan-2010, tatu: [JACKSON-450] Except that if method we saw first is
         *   from an interface, and we now find a non-interface definition, we should
         *   use this method, but with combination of annotations.
         *   This helps (or rather, is essential) with JAXB annotations and
         *   may also result in faster method calls (interface calls are slightly
         *   costlier than regular method calls)
         */
        if (old.getDeclaringClass().isInterface() && !m.getDeclaringClass().isInterface()) {
          methods.add(old.withMethod(m));
        }
      }
    }
  }
  private static Set<MethodInfo> getGetterMethodInfo(Class<?> clazz) {

    Set<MethodInfo> methodInfos = METHOD_MAP.get(clazz);

    if (methodInfos == null) {

      methodInfos = new HashSet<MethodInfo>();

      boolean includeSuperClass = clazz.getClassLoader() != null;

      Method[] methods = includeSuperClass ? clazz.getMethods() : clazz.getDeclaredMethods();

      for (Method method : methods) {
        try {
          if (Modifier.isPublic(method.getModifiers())) {
            String name = method.getName();
            String key = "";
            if (name.startsWith("get")) {
              if ("getClass".equals(name) || "getDeclaringClass".equals(name)) {
                key = "";
              } else {
                key = name.substring(3);
              }
            } else if (name.startsWith("is")) {
              key = name.substring(2);
            }
            if (key.length() > 0
                && Character.isUpperCase(key.charAt(0))
                && method.getParameterTypes().length == 0) {
              if (key.length() == 1) {
                key = key.toLowerCase();
              } else if (!Character.isUpperCase(key.charAt(1))) {
                key = key.substring(0, 1).toLowerCase() + key.substring(1);
              }
              methodInfos.add(new MethodInfo(key, method));
            }
          }
        } catch (Exception ignored) {
        }
      }

      METHOD_MAP.putIfAbsent(clazz, methodInfos);
    }

    return methodInfos;
  }
Example #25
0
  /**
   * 获取对应方法的参数列表
   *
   * @param clazz
   * @param methodName
   * @return
   */
  public static Type[] getParameterTypesByMethodName(Class<?> clazz, String methodName) {
    Method[] methods = clazz.getDeclaredMethods();

    Method me = null;
    for (Method method : methods) {
      if (method.getName().equals(methodName)) {
        me = method;
        break;
      }
    }

    if (me == null) {
      throw new RuntimeException("no such method : " + methodName);
    }

    Type[] types = me.getGenericParameterTypes();
    return types;
  }
 private ArrayList<Object> gatherParamsFromAllMethodsFrom(Class<?> sourceClass) {
   ArrayList<Object> result = new ArrayList<Object>();
   Method[] methods = sourceClass.getDeclaredMethods();
   for (Method method : methods) {
     if (method.getName().startsWith("provide")) {
       if (!Modifier.isStatic(method.getModifiers()))
         throw new RuntimeException(
             "Parameters source method "
                 + method.getName()
                 + " is not declared as static. Modify it to a static method.");
       try {
         result.addAll(Arrays.asList(processParamsIfSingle((Object[]) method.invoke(null))));
       } catch (Exception e) {
         throw new RuntimeException(
             "Cannot invoke parameters source method: " + method.getName(), e);
       }
     }
   }
   return result;
 }
Example #27
0
  private void populateMap(Object bean) {
    final Class klass = bean.getClass();

    // If klass is a System class then set includeSuperClass to false.

    final boolean includeSuperClass = klass.getClassLoader() != null;

    final Method[] methods = (includeSuperClass) ? klass.getMethods() : klass.getDeclaredMethods();
    for (final Method method : methods) {
      try {
        if (Modifier.isPublic(method.getModifiers())) {
          final String name = method.getName();
          String key = "";
          if (name.startsWith("get")) {
            if (name.equals("getClass") || name.equals("getDeclaringClass")) {
              key = "";
            } else {
              key = name.substring(3);
            }
          } else if (name.startsWith("is")) {
            key = name.substring(2);
          }
          if ((key.length() > 0)
              && Character.isUpperCase(key.charAt(0))
              && (method.getParameterTypes().length == 0)) {
            if (key.length() == 1) {
              key = key.toLowerCase();
            } else if (!Character.isUpperCase(key.charAt(1))) {
              key = key.substring(0, 1).toLowerCase() + key.substring(1);
            }

            final Object result = method.invoke(bean, (Object[]) null);
            if (result != null) {
              this.map.put(key, JSONObject.wrap(result));
            }
          }
        }
      } catch (final Exception ignore) {
      }
    }
  }
Example #28
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);
     }
   }
 }
    /**
     * 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;
    }
Example #30
0
  public void addData(Class c) {
    cols.add(ID_COL + " INTEGER PRIMARY KEY");
    rawCols.add(ID_COL);

    for (Field f : c.getDeclaredFields()) {
      if (f.isAnnotationPresent(MetaField.class)) {
        MetaField mf = f.getAnnotation(MetaField.class);
        addMetaField(mf);
      }
    }

    for (Method m : c.getDeclaredMethods()) {
      if (m.isAnnotationPresent(MetaField.class)) {
        MetaField mf = m.getAnnotation(MetaField.class);
        addMetaField(mf);
      }
    }

    cols.add(DATA_COL + " BLOB");
    rawCols.add(DATA_COL);
  }