/**
   * Return the Method object for the given methodName and parameterTypes on the given objClass.
   *
   * @param objClass
   * @param methodName
   * @param parameterTypes
   * @return
   */
  public static Method findMethod(Class objClass, String methodName, Class... parameterTypes) {

    LOG.debug(
        "Looking for method "
            + methodName
            + "("
            + formatClassNames(parameterTypes)
            + ") on "
            + objClass.getName()
            + ".");
    Method result = null;

    Method[] methods = objClass.getDeclaredMethods();
    for (Method m : methods) {

      if (m.getName().compareToIgnoreCase(methodName) == 0) {

        Class[] methodParameterTypes = m.getParameterTypes();
        if (parametersMatch(methodParameterTypes, parameterTypes)) {

          result = m;
          break;
        }
      }
    }

    // Handle collections
    if (result == null) {

      methods = objClass.getDeclaredMethods();
      for (Method m : methods) {

        if (m.getName().compareToIgnoreCase(methodName + "s") == 0) {

          Class[] methodParameterTypes = m.getParameterTypes();
          if (parametersMatch(methodParameterTypes, parameterTypes)) {

            result = m;
            break;
          }
        }
      }
    }

    if (result == null) {
      LOG.debug(
          "Method "
              + methodName
              + "("
              + formatClassNames(parameterTypes)
              + ") on "
              + objClass.getName()
              + " not found.");
    }
    return result;
  }
Example #2
0
  /**
   * Register.
   *
   * @param clazz the clazz
   */
  public static void register(Class<?> clazz) {
    Library annotatedLibrary = clazz.getAnnotation(Library.class);
    if (annotatedLibrary != null) {
      register(annotatedLibrary);
      registerNativeMethods(annotatedLibrary.defaultAPI(), clazz.getDeclaredMethods());
    } else {
      registerNativeMethods(Library.API, clazz.getDeclaredMethods());
    }

    invokeStaticInitializerOnClass(clazz);
  }
 // ===================================================================================
 //                                                                       Set up Method
 //                                                                       =============
 @Override
 protected void setupMethod(S2ActionMapping actionMapping, Class<?> actionClass) {
   // copied from super and adjust a little bit
   S2ExecuteConfig allSelectedExecuteConfig = null;
   for (Class<?> clazz = actionClass; clazz != Object.class; clazz = clazz.getSuperclass()) {
     for (Method method : clazz.getDeclaredMethods()) {
       if (isOutOfTargetMethod(actionMapping, actionClass, method)) {
         continue;
       }
       checkActionMethod(actionClass, method);
       checkDuplicateExecute(actionMapping, actionClass, method);
       final S2ExecuteConfig executeConfig = createExecuteConfig();
       setupExecuteConfig(executeConfig, actionMapping, actionClass, method);
       if (executeConfig.isUrlPatternAllSelected()) {
         if (allSelectedExecuteConfig != null) {
           throw new MultipleAllSelectedUrlPatternRuntimeException(
               allSelectedExecuteConfig.getUrlPattern(), executeConfig.getUrlPattern());
         }
         allSelectedExecuteConfig = executeConfig;
       } else {
         actionMapping.addExecuteConfig(executeConfig);
       }
     }
   }
   registerAllSelectedExecuteConfig(actionMapping, allSelectedExecuteConfig);
   checkExecuteConfigSize(actionMapping, actionClass);
 }
Example #4
0
 public static Method findPreDestroyMethod(Class<?> c, String name) {
   if (Object.class == c || null == c) {
     return null;
   }
   for (Method m : c.getDeclaredMethods()) {
     if (name != null) {
       if (m.getName().equals(name)) {
         return m;
       }
     } else if (m.getAnnotation(PreDestroy.class) != null) {
       return m;
     }
   }
   Method m = findPreDestroyMethod(c.getSuperclass(), name);
   if (m != null) {
     return m;
   }
   for (Class<?> i : c.getInterfaces()) {
     m = findPreDestroyMethod(i, name);
     if (m != null) {
       return m;
     }
   }
   return null;
 }
Example #5
0
  private boolean winShellExecute(final String filePath, final String verb) throws Exception {
    final Class<?> clz = WinAPIWrapper.class;
    Method stringToByteArray = null, shellExecute = null;
    for (final Method m : clz.getDeclaredMethods()) {
      if (m.getName().equals("stringToByteArray")) {
        stringToByteArray = m;
        continue;
      } else if (m.getName().equals("shellExecute")) {
        shellExecute = m;
        continue;
      }
    }
    stringToByteArray.setAccessible(true);
    shellExecute.setAccessible(true);

    byte[] filePathBytes = (byte[]) stringToByteArray.invoke(null, filePath);
    byte[] verbBytes = (byte[]) stringToByteArray.invoke(null, verb);
    final Integer result = (Integer) shellExecute.invoke(null, filePathBytes, verbBytes);
    logger.debug(
        "ShellExecute(NULL, \""
            + verb
            + "\", \""
            + filePath
            + "\", NULL, NULL, SW_SHOWNORMAL); returned "
            + result);
    return (result != null && result.intValue() > 32);
  }
Example #6
0
  public static OptionSchema newOptionSchema(Class<?> optionHolderType) {
    OptionSchema optionSchema = new OptionSchema();

    // traverses through super classes
    for (Class<?> optionHolderClass = optionHolderType;
        optionHolderClass != null;
        optionHolderClass = optionHolderClass.getSuperclass()) {
      // looks for bean methods annotated with Option or Argument
      for (Method eachMethod : optionHolderClass.getDeclaredMethods()) {
        if (eachMethod.getAnnotation(Option.class) != null) optionSchema.addOptionItem(eachMethod);

        if (eachMethod.getAnnotation(Argument.class) != null)
          optionSchema.addArgumentItem(eachMethod);
      }

      // looks for bean fields annotated with Option or Argument
      for (Field f : optionHolderClass.getDeclaredFields()) {
        if (f.getAnnotation(Option.class) != null) optionSchema.addOptionItem(f);

        if (f.getAnnotation(Argument.class) != null) optionSchema.addArgumentItem(f);
      }

      if (optionHolderClass.getAnnotation(Usage.class) != null) {
        optionSchema.setUsage(optionHolderClass);
      }
    }

    return optionSchema;
  }
Example #7
0
  /**
   * bean对象转Map
   *
   * @param obj 实例对象
   * @return map集合
   */
  public static Map<String, String> beanToMap(Object obj) {
    Class<?> cls = obj.getClass();
    Map<String, String> valueMap = new HashMap<String, String>();
    // 取出bean里的所有方法
    Method[] methods = cls.getDeclaredMethods();
    Field[] fields = cls.getDeclaredFields();
    for (Field field : fields) {
      try {
        String fieldType = field.getType().getSimpleName();
        String fieldGetName = parseMethodName(field.getName(), "get");
        if (!haveMethod(methods, fieldGetName)) {
          continue;
        }
        Method fieldGetMet = cls.getMethod(fieldGetName, new Class[] {});
        Object fieldVal = fieldGetMet.invoke(obj, new Object[] {});
        String result = null;
        if ("Date".equals(fieldType)) {
          SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
          result = sdf.format((Date) fieldVal);

        } else {
          if (null != fieldVal) {
            result = String.valueOf(fieldVal);
          }
        }
        valueMap.put(field.getName(), result);
      } catch (Exception e) {
        continue;
      }
    }
    return valueMap;
  }
Example #8
0
 /**
  * Bean转换为Map
  *
  * @param <T>
  * @param pojo
  * @return Map
  */
 public static <T> Map<String, Object> converBean2Map(T pojo) {
   Map<String, Object> rtnMap = new HashMap<String, Object>();
   Class<? extends Object> classType = pojo.getClass();
   // bean方法
   Method[] methods = classType.getDeclaredMethods();
   try {
     // 获取所有get方法
     for (Method method : methods) {
       String methodName = method.getName();
       if (methodName.startsWith(GET)) {
         // 获取属性名
         String filedName = methodName.substring(GET.length());
         StringBuffer sb = new StringBuffer();
         sb.append(filedName.substring(0, 1).toLowerCase()).append(filedName.substring(1));
         // Map数据摄值
         rtnMap.put(sb.toString(), method.invoke(pojo));
       }
     }
   } catch (IllegalArgumentException e) {
     log.error(e.getMessage(), e);
   } catch (IllegalAccessException e) {
     log.error(e.getMessage(), e);
   } catch (InvocationTargetException e) {
     log.error(e.getMessage(), e);
   }
   return rtnMap;
 }
Example #9
0
    /**
     * Creates an action method list for a controller class. The methods of the controller class are
     * scanned, all action methods are extracted from the controller class and then joined with all
     * inherited action methods of the parent list.
     *
     * @param controllerClass the controller class
     * @param parentList the method list of the parent class
     * @param typeLib a type library.
     */
    public CMethods(
        Class<? extends Controller> controllerClass,
        String methodPath,
        CMethods parentList,
        PathParamMap pathParams,
        TypeLib typeLib) {
      this(controllerClass, methodPath, parentList.factory_, parentList.hierarchLevel_ + 1);
      Check.notNull(parentList, "parentList");

      // add inheritable action methods
      for (LeveledMethod m : parentList.methods_) {
        if (m.method.canInherit(controllerClass)) methods_ = ArrayUtil.addLast(methods_, m);
      }

      // add action methods defined by the controller class
      MethodArgFactory argFactory = new MethodArgFactory(pathParams, typeLib);
      int inClassIndex = 0;
      for (Method javaMethod : controllerClass.getDeclaredMethods()) {
        Path pathAnno = javaMethod.getAnnotation(Path.class);
        if (pathAnno == null ? methodPath == null : pathAnno.value().equals(methodPath)) {
          ControllerMethod method = ControllerMethod.create(argFactory, javaMethod);
          if (method != null)
            methods_ =
                ArrayUtil.addLast(
                    methods_, new LeveledMethod(method, hierarchLevel_, inClassIndex++));
        }
      }

      Arrays.sort(methods_);
    }
  /**
   * This factory method takes a SearchConfiguration object and returns a SearchMapping object which
   * defines the programmatic model for indexing entities and fields.
   *
   * <p>Throws SearchException: 1) No @Factory found 2) Multiple @Factory found 3)
   * hibernate.search.model_mapping defines a class that cannot be found 4) Cannot invoke
   * the @Factory method to get new instance of SearchMapping
   *
   * @param cfg the search configuration
   * @return SearchMapping
   */
  public static SearchMapping getSearchMapping(SearchConfiguration cfg) {

    // try SearchConfiguration object first and then properties
    Object modelMappingProperty = cfg.getProgrammaticMapping();
    if (modelMappingProperty == null) {
      modelMappingProperty = cfg.getProperties().get(Environment.MODEL_MAPPING);
    }

    if (modelMappingProperty == null) {
      return null;
    }
    SearchMapping mapping = null;
    Object programmaticConfig = modelMappingProperty;
    if (programmaticConfig instanceof SearchMapping) {
      mapping = (SearchMapping) programmaticConfig;
      return mapping;
    }
    Class<?> clazz = getProgrammaticMappingClass(programmaticConfig);
    Method[] methods = clazz.getDeclaredMethods();
    int count = 0;
    for (Method method : methods) {
      if (method.isAnnotationPresent(Factory.class)) {
        count++;
        ReflectionHelper.setAccessible(method);
        mapping = getNewInstanceOfSearchMapping(clazz, method);
      }
    }
    validateMappingFactoryDefinition(count, clazz);
    return mapping;
  }
Example #11
0
  /**
   * reads all methods by the action-annotations for building agent-actions
   *
   * @param p_class class
   * @param p_root root class
   * @return stream of all methods with inheritance
   */
  private static Stream<Method> methods(final Class<?> p_class, final Class<?> p_root) {
    final Pair<Boolean, IAgentAction.EAccess> l_classannotation = CCommon.isActionClass(p_class);
    if (!l_classannotation.getLeft())
      return p_class.getSuperclass() == null
          ? Stream.of()
          : methods(p_class.getSuperclass(), p_root);

    final Predicate<Method> l_filter =
        IAgentAction.EAccess.WHITELIST.equals(l_classannotation.getRight())
            ? i -> !CCommon.isActionFiltered(i, p_root)
            : i -> CCommon.isActionFiltered(i, p_root);

    return Stream.concat(
        Arrays.stream(p_class.getDeclaredMethods())
            .parallel()
            .map(
                i -> {
                  i.setAccessible(true);
                  return i;
                })
            .filter(i -> !Modifier.isAbstract(i.getModifiers()))
            .filter(i -> !Modifier.isInterface(i.getModifiers()))
            .filter(i -> !Modifier.isNative(i.getModifiers()))
            .filter(i -> !Modifier.isStatic(i.getModifiers()))
            .filter(l_filter),
        methods(p_class.getSuperclass(), p_root));
  }
Example #12
0
 @Override
 public Object __tojava__(Class<?> c) {
   // Automatically coerce to single method interfaces
   if (c.isInstance(this) && c != InvocationHandler.class) {
     // for base types, conversion is simple - so don't wrap!
     // InvocationHandler is special, since it's a single method interface
     // that we implement, but if we coerce to it we want the arguments
     return c.cast(this);
   } else if (c.isInterface()) {
     if (c.getDeclaredMethods().length == 1 && c.getInterfaces().length == 0) {
       // Proper single method interface
       return proxy(c);
     } else {
       // Try coerce to interface with multiple overloaded versions of
       // the same method (name)
       String name = null;
       for (Method method : c.getMethods()) {
         if (method.getDeclaringClass() != Object.class) {
           if (name == null || name.equals(method.getName())) {
             name = method.getName();
           } else {
             name = null;
             break;
           }
         }
       }
       if (name != null) { // single unique method name
         return proxy(c);
       }
     }
   }
   return super.__tojava__(c);
 }
Example #13
0
 protected void copyInFields(Item copyFrom) {
   Class copyFromClass = copyFrom.getClass();
   Class copyToClass = this.getClass();
   for (Method methodFrom : copyFromClass.getDeclaredMethods()) {
     String setMethodName = null;
     if (methodFrom.getName().startsWith("get")) {
       setMethodName = "set" + methodFrom.getName().substring(3, methodFrom.getName().length());
     } else if (methodFrom.getName().startsWith("is")) {
       setMethodName = "set" + methodFrom.getName().substring(2, methodFrom.getName().length());
     }
     if (setMethodName != null) {
       try {
         Method methodTo = copyToClass.getMethod(setMethodName, methodFrom.getReturnType());
         try {
           methodTo.invoke(this, methodFrom.invoke(copyFrom, null));
         } catch (Exception e) {
           // logger.error("Could not copy field from method: " + methodFrom.getName(), e);
         }
       }
       // No setter, do nothing.
       catch (NoSuchMethodException e) {
       }
     }
   }
 }
Example #14
0
  private Method getMethodObject(Class c) throws Throwable {
    int found = 0;
    Method result = null;
    Method[] methods = c.getDeclaredMethods();
    for (int i = 0; i < methods.length; i++) {
      Method method = methods[i];
      if (LOG.isDebugEnabled()) {
        LOG.debug(
            "Checking reflected method name '"
                + method.getName()
                + "' vs. supplied method name '"
                + getMethod()
                + "'");
      }

      if (method.getName().equals(getMethod())
          && isEquivalent(toClassArray(args), method.getParameterTypes())) {
        if (result != null) {
          found++;
        }
        result = method;

        if (LOG.isDebugEnabled()) {
          LOG.debug("Matched method '" + method + "'");
        }
      }
    }

    if (found > 1) {
      LOG.warn("" + found + " method signatures matched specified method!");
    }

    return result;
  }
  private boolean methodRegistration(
      Named owner, Class<?> commands, Object instance, org.spout.api.command.Command parent) {
    boolean success = true;
    for (Method method : commands.getDeclaredMethods()) {
      // Basic checks
      method.setAccessible(true);
      if (!Modifier.isStatic(method.getModifiers()) && instance == null) {
        continue;
      }
      org.spout.api.command.Command child = createCommand(owner, parent, method);
      if (child == null) {
        continue;
      }

      if (method.isAnnotationPresent(NestedCommand.class)) {
        for (Class<?> clazz : method.getAnnotation(NestedCommand.class).value()) {
          success &= create(owner, clazz, child);
        }
      } else {
        child.setExecutor(executorFactory.getAnnotatedCommandExecutor(instance, method));
      }
      child.closeSubCommand();
    }
    return success;
  }
  public String doGetClassMethods() throws Exception {
    StringBuffer document = new StringBuffer();
    try {
      Class cls = null;
      if (className == null || className.equals("$templateLogic"))
        cls = BasicTemplateController.class;
      else if (className.equals("$componentLogic")) cls = ComponentLogic.class;
      else cls = Class.forName(className);

      if (cls == null) return out("<methods class=\"null\" package=\"null\"/>");

      document.append(
          "<methods class=" + q(cls.getName()) + " package=" + q(cls.getPackage().getName()) + ">");
      Method m[] = cls.getDeclaredMethods();
      for (int i = 0; i < m.length; i++) {
        Method method = m[i];
        if (Modifier.isPublic(method.getModifiers())) {
          document.append(createMethodElement(method));
        }
      }
      document.append("</methods>");
    } catch (Throwable e) {
      System.err.println(e);
      return out("<methods class=\"null\" package=\"null\"/>");
    }

    return out(document.toString());
  }
 public static Method findGetterForPropertyName(Class<?> resourceClass, String propertyName) {
   Class<?> currentResourceClass = resourceClass;
   do {
     for (Method method : currentResourceClass.getDeclaredMethods()) {
       if (method.getParameterTypes().length == 0) {
         String methodName = method.getName();
         int methodNameLength = methodName.length();
         if (((methodName.startsWith(METHOD_NAME_GET))
                 && (methodNameLength > METHOD_NAME_GET.length()))
             || ((methodName.startsWith(METHOD_NAME_IS))
                 && (methodNameLength > METHOD_NAME_IS.length()))) {
           PropertyDescription propertyDescriptionAnnotation =
               ReflectionHelper.getAnnotation(method, PropertyDescription.class);
           if (propertyDescriptionAnnotation != null) {
             String propertyDescriptionName = propertyDescriptionAnnotation.name();
             if (propertyName.equals(propertyDescriptionName)) {
               return method;
             }
           }
         }
       }
     }
     currentResourceClass = currentResourceClass.getSuperclass();
   } while (currentResourceClass != null);
   throw new IllegalArgumentException(
       NLS.bind(
           "Could not find property named {0} in {1}",
           new Object[] {propertyName, resourceClass}));
 }
Example #18
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;
      }
    }
  }
Example #19
0
 public boolean isSynchronized(Class cls) {
   Method[] methods = cls.getDeclaredMethods();
   for (int i = 0; i < methods.length; i++) {
     if (isPublicAndNotSynchronized(methods[i])) return false;
   }
   return true;
 }
Example #20
0
 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));
     }
   }
 }
Example #21
0
 private static Map<String, Method> addMethods(
     Map<String, Method> methods, Class<?> clazz, Predicate<Method> filter) {
   requireNonNull(methods);
   requireNonNull(filter);
   // clazz nullable (why?)
   if (clazz == Object.class) {
     return methods;
   }
   if (clazz == null) {
     return methods;
   }
   Stream.of(clazz.getDeclaredMethods())
       .filter(filter)
       .forEach(
           m -> {
             methods.putIfAbsent(m.getName(), m); // Put only the most recent
             // concrete version of the
             // method
           });
   addMethods(methods, clazz.getSuperclass(), filter); // Recursively add
   // the superclass
   // methods
   Stream.of(clazz.getInterfaces())
       .forEach(
           i -> {
             addMethods(methods, i, filter); // Recursively add the extended
             // interfaces (because they can
             // contain default methods)
           });
   return methods;
 }
  public Class<?> getClassInstance(String name) throws ClassNotFoundException {
    Class<?> clazz = super.getClassInstance(name);

    synchronized (this) {
      if (strutsInjector == null) {
        // We can only bind each class once.
        if (!boundClasses.contains(clazz)) {
          try {
            // Calling these methods now helps us detect ClassNotFoundErrors
            // early.
            clazz.getDeclaredFields();
            clazz.getDeclaredMethods();

            boundClasses.add(clazz);
          } catch (Throwable t) {
            // Struts should still work even though some classes aren't in the
            // classpath. It appears we always get the exception here when
            // this is the case.
            return clazz;
          }
        }
      }
    }

    return clazz;
  }
Example #23
0
  /**
   * 反序列化简单对象
   *
   * @param jo json对象
   * @param clazz 实体类类型
   * @return 反序列化后的实例
   * @throws JSONException
   */
  public static <T> T parseObject(JSONObject jo, Class<T> clazz) throws JSONException {
    if (clazz == null || isNull(jo)) {
      return null;
    }

    T obj = newInstance(clazz);
    if (obj == null) {
      return null;
    }
    if (isMap(clazz)) {
      setField(obj, jo);
    } else {
      // 取出bean里的所有方法
      Method[] methods = clazz.getDeclaredMethods();
      Field[] fields = clazz.getDeclaredFields();
      for (Field f : fields) {
        String setMetodName = parseMethodName(f.getName(), "set");
        if (!haveMethod(methods, setMetodName)) {
          continue;
        }
        try {
          Method fieldMethod = clazz.getMethod(setMetodName, f.getType());
          setField(obj, fieldMethod, f, jo);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    return obj;
  }
Example #24
0
  @SuppressWarnings("rawtypes")
  public static ApiObjectDoc buildFromAnnotation(ApiObject annotation, Class clazz) {

    final List<ApiObjectFieldDoc> fieldDocs = new ArrayList<ApiObjectFieldDoc>();
    for (Field field : clazz.getDeclaredFields())
      if (field.getAnnotation(ApiObjectField.class) != null)
        fieldDocs.add(
            ApiObjectFieldDoc.buildFromAnnotation(
                field.getAnnotation(ApiObjectField.class), field));

    for (Method getter : clazz.getDeclaredMethods())
      if (getter.getAnnotation(ApiObjectGetter.class) != null
          && getter.getName().startsWith("get")
          && getter.getParameterTypes().length == 0)
        fieldDocs.add(
            ApiObjectFieldDoc.buildFromAnnotation(
                getter.getAnnotation(ApiObjectGetter.class), getter));

    Class<?> c = clazz.getSuperclass();
    if (c != null) {
      if (c.isAnnotationPresent(ApiObject.class)) {
        ApiObjectDoc objDoc = ApiObjectDoc.buildFromAnnotation(c.getAnnotation(ApiObject.class), c);
        fieldDocs.addAll(objDoc.getFields());
      }
    }

    return new ApiObjectDoc(annotation.name(), annotation.description(), fieldDocs);
  }
Example #25
0
  /** List all class methods, including inherited and private. Inheritance duplicates cleared */
  public List<JaversMethod> getAllMethods() {
    List<JaversMethod> methods = new ArrayList<>();
    Set<Integer> added = new HashSet<>();
    TypeResolvingContext context = new TypeResolvingContext();

    Class clazz = methodSource;
    while (clazz != null) {
      context.addTypeSubstitutions(clazz);
      for (Method m : clazz.getDeclaredMethods()) {
        if (m.isBridge()) {
          continue;
        }
        int methodKey = methodKey(m);
        if (added.contains(methodKey)) {
          // System.out.println("filtered inheritance duplicate" +m);
          continue;
        }
        methods.add(createJMethod(m, context));
        added.add(methodKey);
      }
      clazz = clazz.getSuperclass();
    }

    return methods;
  }
Example #26
0
  /**
   * Searches a method with a similar signature as desired using {@link #isSimilarSignature(Method,
   * String, Class[])}.
   *
   * <p>First public methods are searched in the class hierarchy, then private methods on the
   * declaring class. If a method could be found, it is returned, otherwise a {@code
   * NoSuchMethodException} is thrown.
   */
  private Method similarMethod(String name, Class<?>[] types) throws NoSuchMethodException {
    Class<?> type = type();

    // first priority: find a public method with a "similar" signature in class hierarchy
    // similar interpreted in when primitive argument types are converted to their wrappers
    for (Method method : type.getMethods()) {
      if (isSimilarSignature(method, name, types)) {
        return method;
      }
    }

    // second priority: find a non-public method with a "similar" signature on declaring class
    do {
      for (Method method : type.getDeclaredMethods()) {
        if (isSimilarSignature(method, name, types)) {
          return method;
        }
      }

      type = type.getSuperclass();
    } while (type != null);

    throw new NoSuchMethodException(
        "No similar method "
            + name
            + " with params "
            + Arrays.toString(types)
            + " could be found on type "
            + type()
            + ".");
  }
Example #27
0
 /**
  * Get a method by name.
  * 
  * @param c  class object
  * @param methodName  method name
  * @param argTypes  argument types
  * @return  method object, or null if it does not exist
  */
 public static Method getDeclaredMethod(Class c, String methodName, Class[] argTypes) {
     Method m;
     try {
         if (argTypes != null) {
             m = c.getMethod(methodName, argTypes);
         } else {
             m = null;
             Method[] ms = c.getDeclaredMethods();
             for (int i = 0; i < ms.length; ++i) {
                 if (ms[i].getName().equals(methodName)) {
                     m = ms[i];
                     break;
                 }
             }
             if (m == null) {
                 System.err.println("Can't find "+c.getName()+"."+methodName);
                 return null;
             }
         }
         try {
             m.setAccessible(true);
         } catch (AccessControlException _) { }
     } catch (SecurityException e1) {
         System.err.println("Cannot access "+c.getName()+"."+methodName);
         e1.printStackTrace();
         return null;
     } catch (NoSuchMethodException e1) {
         System.err.println("Can't find "+c.getName()+"."+methodName);
         e1.printStackTrace();
         return null;
     }
     return m;
 }
Example #28
0
  private void checkCompoundIds(Class<?> javaClass) throws IOException {
    String javaClassName = javaClass.getCanonicalName();
    PsiClass psiClass =
        myJavaPsiFacade.findClass(
            javaClassName, GlobalSearchScope.moduleWithLibrariesScope(myModule));
    assertNotNull(psiClass);

    for (java.lang.reflect.Method javaMethod : javaClass.getDeclaredMethods()) {
      Method method =
          new Method(
              Type.getType(javaClass).getInternalName(),
              javaMethod.getName(),
              Type.getMethodDescriptor(javaMethod));
      boolean noKey = javaMethod.getAnnotation(ExpectNoPsiKey.class) != null;
      PsiMethod psiMethod = psiClass.findMethodsByName(javaMethod.getName(), false)[0];
      checkCompoundId(method, psiMethod, noKey);
    }

    for (Constructor<?> constructor : javaClass.getDeclaredConstructors()) {
      Method method =
          new Method(
              Type.getType(javaClass).getInternalName(),
              "<init>",
              Type.getConstructorDescriptor(constructor));
      boolean noKey = constructor.getAnnotation(ExpectNoPsiKey.class) != null;
      PsiMethod[] constructors = psiClass.getConstructors();
      PsiMethod psiMethod = constructors[0];
      checkCompoundId(method, psiMethod, noKey);
    }
  }
Example #29
0
  public static void main(String[] args) throws Exception {
    Do_Not_Terminate.forbidExit();

    try {
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      int num = Integer.parseInt(br.readLine().trim());
      Object o; // Must be used to hold the reference of the instance of
      // the class Solution.Inner.Private

      Inner in = new Inner();
      o = in.new Private();
      Class<?> clz = Class.forName(Solution3.class.getName() + "$Inner$Private");
      for (Method m : clz.getDeclaredMethods()) {
        if (m.getName().indexOf("powerof2") > -1) {
          m.setAccessible(true);
          System.out.println(num + " is " + m.invoke(o, num));
        }
      }

      // TODO
      System.out.println(
          "An instance of class: " + o.getClass().getCanonicalName() + " has been created");

    } // end of try
    catch (Do_Not_Terminate.ExitTrappedException e) {
      System.out.println("Unsuccessful Termination!!");
    }
  } // end of main
 private static Method getMethod(
     Class<?> controllerType, String methodName, Object... argumentValues) {
   Method match = null;
   for (Method method : controllerType.getDeclaredMethods()) {
     if (method.getName().equals(methodName)
         && method.getParameterTypes().length == argumentValues.length) {
       if (match != null) {
         throw new IllegalArgumentException(
             "Found two methods named '"
                 + methodName
                 + "' having "
                 + Arrays.asList(argumentValues)
                 + " arguments, controller "
                 + controllerType.getName());
       }
       match = method;
     }
   }
   if (match == null) {
     throw new IllegalArgumentException(
         "No method '"
             + methodName
             + "' with "
             + argumentValues.length
             + " parameters found in "
             + controllerType.getName());
   }
   return match;
 }