Пример #1
0
  private final void bindResourceToLocalContainer(
      final Class<?> resource, final Class<?> container) {
    final Set<Method> nonAbstractMethods =
        Sets.newHashSet(resource.getMethods())
            .stream()
            .filter(method -> !Modifier.isAbstract(method.getModifiers()))
            .collect(Collectors.toSet());
    Preconditions.checkState(
        !nonAbstractMethods.isEmpty(),
        "Found non-abstract methods in " + resource + ": " + nonAbstractMethods);

    final Set<Method> abstractMethods =
        Sets.newHashSet(resource.getMethods())
            .stream()
            .filter(method -> Modifier.isAbstract(method.getModifiers()))
            .collect(Collectors.toSet());

    for (final Method resourceMethod : abstractMethods) {
      final Method containerMethod = findMatchingMethod(container, resourceMethod);
      if (containerMethod != null) {
        this.resourceToContainer.put(resourceMethod, containerMethod);
      }
    }

    bindResourceToContainer(resource, injector.getInstance(container));
  }
  public OutputPipeInvocationHandler(Pipe outputRing, int msgIdx, Class<?> clazz) {
    super(clazz.getMethods());

    FieldReferenceOffsetManager from = Pipe.from(outputRing);
    final Method[] methods = clazz.getMethods();

    writers = new OutputPipeWriterMethod[MAX_METHODS];
    int j = methods.length;
    while (--j >= 0) {
      final Method method = methods[j];
      ProngTemplateField fieldAnnonation = method.getAnnotation(ProngTemplateField.class);
      if (null != fieldAnnonation) {

        int fieldLoc =
            FieldReferenceOffsetManager.lookupFieldLocator(fieldAnnonation.fieldId(), msgIdx, from);

        int key = buildKey(this, method.getName());
        if (null != writers[key]) {
          throw new UnsupportedOperationException();
        }
        writers[key] =
            OutputPipeWriterMethod.buildWriteForYourType(
                outputRing,
                fieldAnnonation.decimalPlaces(),
                fieldLoc,
                (fieldLoc >> FieldReferenceOffsetManager.RW_FIELD_OFF_BITS)
                    & TokenBuilder.MASK_TYPE,
                from);
      }
    }
  }
Пример #3
0
  public WrapperHelper createWrapperHelper(
      Class<?> wrapperType,
      QName wrapperName,
      List<String> partNames,
      List<String> elTypeNames,
      List<Class<?>> partClasses) {

    List<Method> getMethods = new ArrayList<Method>(partNames.size());
    List<Method> setMethods = new ArrayList<Method>(partNames.size());
    List<Field> fields = new ArrayList<Field>(partNames.size());

    Method allMethods[] = wrapperType.getMethods();

    for (int x = 0; x < partNames.size(); x++) {
      String partName = partNames.get(x);
      if (partName == null) {
        getMethods.add(null);
        setMethods.add(null);
        fields.add(null);
        continue;
      }

      String getAccessor = JAXBUtils.nameToIdentifier(partName, JAXBUtils.IdentifierType.GETTER);
      String setAccessor = JAXBUtils.nameToIdentifier(partName, JAXBUtils.IdentifierType.SETTER);
      Method getMethod = null;
      Method setMethod = null;
      Class<?> valueClass = XmlBeansWrapperHelper.getXMLBeansValueType(wrapperType);
      allMethods = valueClass.getMethods();

      try {
        getMethod = valueClass.getMethod(getAccessor, AbstractWrapperHelper.NO_CLASSES);
      } catch (NoSuchMethodException ex) {
        // ignore for now
      }

      for (Method method : allMethods) {
        if (method.getParameterTypes() != null
            && method.getParameterTypes().length == 1
            && (setAccessor.equals(method.getName()))) {
          setMethod = method;
          break;
        }
      }

      getMethods.add(getMethod);
      setMethods.add(setMethod);
      // There is no filed in the XMLBeans type class
      fields.add(null);
    }

    return new XmlBeansWrapperHelper(
        wrapperType,
        setMethods.toArray(new Method[setMethods.size()]),
        getMethods.toArray(new Method[getMethods.size()]),
        fields.toArray(new Field[fields.size()]));
  }
  /**
   * Creates a support map that maintain for each method name (name as key) a list of Methods found
   * in the Class.
   */
  @SuppressWarnings("deprecation")
  private Map<String, List<Method>> buildAnnotatedMethodsCache(Class<?> clazz) {
    ClassLoader ctxClassLoader = Thread.currentThread().getContextClassLoader();
    IProject currProj = JDTUtils.getCurrentProjectForOpenEditor();
    String classCanonicalName = clazz.getCanonicalName();
    if (currProj != null
        && !classCanonicalName.startsWith("net.sf.jasperreports.functions.standard")) {
      // Try to reload a fresh new instance of the Class instance.
      // Useful for code being developed directly inside JSS.
      // We skip the standard ones contributed via jar.
      OutputFolderClassLoader reloaderCL =
          new OutputFolderClassLoader(JavaCore.create(currProj), ctxClassLoader);
      Class<?> reloadedClazz = reloaderCL.reloadClass(clazz.getCanonicalName());
      if (reloadedClazz != null) {
        clazz = reloadedClazz;
      }
    }

    Map<String, List<Method>> methodsByNameMap = new HashMap<String, List<Method>>();

    // First round locate all methods with the JRFunction annotation
    // in order to have a list of what will be the functions
    for (Method m : clazz.getMethods()) {
      JRExprFunction jrFunctionAnn = m.getAnnotation(JRExprFunction.class);
      Function jrNewFunctionAnn = m.getAnnotation(Function.class);
      if (jrNewFunctionAnn != null || jrFunctionAnn != null) {
        String methodName = m.getName();
        List<Method> methods = methodsByNameMap.get(methodName);
        if (methods == null) {
          methods = new ArrayList<Method>();
        }
        methods.add(m);
        methodsByNameMap.put(methodName, methods);
      }
    }

    // After that enrich the map with the remaining methods that have the same function
    // name but a different list of parameters
    for (Method m : clazz.getMethods()) {
      JRExprFunction jrFunctionAnn = m.getAnnotation(JRExprFunction.class);
      Function jrNewFunctionAnn = m.getAnnotation(Function.class);
      if (jrNewFunctionAnn == null || jrFunctionAnn == null) {
        String methodName = m.getName();
        List<Method> methods = methodsByNameMap.get(methodName);
        if (methods != null) {
          methods.add(m);
        }
      }
    }

    return methodsByNameMap;
  }
Пример #5
0
 private MetaClass skipTokens(LinkedList<String> tokens, MetaClass metaClass) {
   while (tokens.size() > 1) {
     Class theClass = metaClass.getTheClass();
     String token = tokens.pollFirst();
     Class selectedClass = null;
     if (propertyPattern.matcher(token).matches()) {
       String getterName = "get" + StringGroovyMethods.capitalize((CharSequence) token);
       for (MetaMethod metaMethod : metaClass.getMetaMethods()) {
         if (metaMethod.getName().equals(getterName)) {
           selectedClass = metaMethod.getReturnType();
           break;
         }
       }
       if (selectedClass == null)
         for (Method method : theClass.getMethods()) {
           if (method.getParameterTypes().length != 0) continue;
           if (method.getName().equals(getterName)) {
             selectedClass = method.getReturnType();
             break;
           }
         }
       if (selectedClass == null) {
         MetaProperty metaProperty = metaClass.getMetaProperty(token);
         if (metaProperty == null) return null;
         selectedClass = metaProperty.getType();
       }
     } else if (methodPattern.matcher(token).matches()) {
       String curMethodName = token.substring(0, token.indexOf('('));
       for (MetaMethod metaMethod : metaClass.getMetaMethods()) {
         String name = metaMethod.getName();
         if (name.equals(curMethodName)) {
           selectedClass = metaMethod.getReturnType();
           break;
         }
       }
       if (selectedClass == null)
         for (Method method : theClass.getMethods()) {
           String name = method.getName();
           if (name.equals(curMethodName)) {
             selectedClass = method.getReturnType();
             break;
           }
         }
     }
     if (selectedClass == null) return null;
     metaClass = InvokerHelper.getMetaClass(selectedClass);
   }
   return metaClass;
 }
Пример #6
0
 private static <C> Method getAdder(Class<C> klass, Field field) {
   Method[] methods = klass.getMethods();
   for (Method method : methods) {
     if (isAdder(method, field.getName())) return method;
   }
   return null;
 }
Пример #7
0
 protected Method findMatchingMethod(Class<?> owner, String name, Object... args) {
   List<Method> methods = new ArrayList<Method>();
   for (Method m : owner.getMethods()) {
     if (m.getName().equals(name)) {
       if (isCompatible(m.getParameterTypes(), args)) {
         methods.add(m);
       }
     }
   }
   if (methods.isEmpty()) {
     return null;
   }
   Collections.sort(
       methods,
       new Comparator<Method>() {
         @Override
         public int compare(Method o1, Method o2) {
           int sum = 0;
           for (Class c0 : o1.getParameterTypes()) {
             for (Class c1 : o2.getParameterTypes()) {
               sum += classDist(c0, c1);
             }
           }
           return sum;
         }
       });
   //noinspection unchecked
   return methods.get(0);
 }
  /**
   * Reads data
   *
   * @param classFile the file name of the java bytecode file containing the transfer instructions
   *     so, preprocessed by, apertium-preprocess-transfer-bytecode-j (.class)
   * @param datafile same file, preprocessed by, apertium-preprocess-transfer (.bin)
   * @param bilFstFile bilingual FST file - might be null
   * @throws ClassNotFoundException
   * @throws IllegalAccessException
   * @throws InstantiationException
   * @throws IOException
   */
  @SuppressWarnings("unchecked")
  public void read(Class<?> transferClass, String datafile, String bilFstFile)
      throws IOException, InstantiationException, IllegalAccessException {

    InputStream is = openInFileStream(datafile);
    readData(is);
    is.close();

    Method[] mets = transferClass.getMethods();
    rule_map = new Method[mets.length];

    // Find all methods starting with name 'rule'
    // So the array of rule_map Method is taken by introspection, taking all methods beginning with
    // rule<number>,
    // like rule0__la__num_ord__de__monato, rule1__de_ekde__tempo etc etc and kicks them into the
    // array.
    for (Method method : mets) {
      String name = method.getName();
      if (!name.startsWith("rule")) continue;
      int number = Integer.parseInt(name.substring(4, name.indexOf('_', 5)));
      rule_map[number] = method;
      System.out.print("M" + method);
      if (DEBUG)
        System.err.println(
            method.getName() + "  - #words=" + method.getParameterTypes().length / 2);
    }

    transferObject = (GeneratedTransferBase) transferClass.newInstance();
    transferObject.debug = DEBUG;
    transferObject.init();

    if (bilFstFile != null && bilFstFile.length() > 0) {
      readBil(bilFstFile);
    }
  }
  private Method[] getMethods() {
    Class cl = occupant.getClass();
    Method[] methods = cl.getMethods();

    Arrays.sort(
        methods,
        new Comparator<Method>() {
          public int compare(Method m1, Method m2) {
            int d1 = depth(m1.getDeclaringClass());
            int d2 = depth(m2.getDeclaringClass());
            if (d1 != d2) return d2 - d1;
            int d = m1.getName().compareTo(m2.getName());
            if (d != 0) return d;
            d1 = m1.getParameterTypes().length;
            d2 = m2.getParameterTypes().length;
            return d1 - d2;
          }

          private int depth(Class cl) {
            if (cl == null) return 0;
            else return 1 + depth(cl.getSuperclass());
          }
        });
    return methods;
  }
  /**
   * Add a class to the map
   *
   * @param clazz
   * @return
   */
  public BeanMethodMapBuilder addClass(Class<?> clazz) {

    LOGGER.debug("processing class [{}]", clazz);
    for (Method lMethod : clazz.getMethods()) {

      final boolean lIsBeanMethod =
          lMethod.getParameterTypes().length == 0
              && lMethod.getName().startsWith("get")
              && lMethod.getDeclaringClass() == clazz;

      if (!lIsBeanMethod) {
        continue;
      }

      final String lPropName = lMethod.getName().substring(3);

      LOGGER.debug("processing beanproperty [{}] for class [{}]", lPropName, clazz);

      if (lPropName.length() > 0) {
        mMethodsOrdered.add(lPropName);
        mMethodCache.getUnchecked(lPropName).add(lMethod);
      }
    }
    return this;
  }
 // This finds the reflection method for a given name and parameter count and returns its return
 // type.
 // This assumes the methods have no overload on argument types, else it returns a non-existent
 // type to be corrected manually
 // If the method returns void, an exception is thrown as this shouldn't be happening. An
 // exception is also
 // thrown if the class isn't in the class path, which shouldn't happen either
 private static Type getReturnType(String methodName, int paramCount) {
   final Class<?> _class;
   try {
     _class =
         Class.forName(
             StateMachine.getInstance().getPackageName() + "." + getMachineClassName());
   } catch (ClassNotFoundException exception) {
     throw new RuntimeException("Expected state machine class to be in classpath", exception);
   }
   final Method[] methods = _class.getMethods();
   Type match = null;
   for (Method method : methods) {
     // Check for name match
     if (method.getName().equals(methodName)) {
       final int count = method.getParameterTypes().length;
       // Check for param count match, taking into account possible vararg expansion
       if (method.isVarArgs() ? count <= paramCount : count == paramCount) {
         if (match != null) {
           // Got a previous match, so we have an overload conflict on param types
           // This is hard to resolve, just give up, let the user figure it out
           return new ClassOrInterfaceType("FixMeType");
         }
         // Found a (so far) unique match, get the return type
         final Class<?> returnType = method.getReturnType();
         if (returnType == void.class) {
           throw new IllegalStateException("Getter shouldn't be returning void: " + methodName);
         }
         match = fromClass(returnType);
       }
     }
   }
   // We only get here if we find a unique method match
   return match;
 }
Пример #12
0
 /**
  * * 保存实体
  *
  * @param entity 实体类
  * @param keyName 实体类中获取主键的方法名字, 例如:getId<br>
  *     当为空时({@link StringUtils#isBlank(CharSequence)}),系统会自动找出注解有{@link
  *     javax.persistence.Id}的方法(即主键的get方法)
  * @return 返回保存实体的主键
  */
 public Object save(final T entity, String keyName) {
   entityManager.persist(entity);
   Object o = null;
   try {
     if (StringUtils.isNotBlank(keyName)) {
       o = clazz.getMethod(keyName).invoke(entity);
     } else {
       for (Method m1 : clazz.getMethods()) {
         if (m1.isAnnotationPresent(javax.persistence.Id.class)) {
           o = m1.invoke(entity);
           break;
         }
       }
     }
   } catch (SecurityException e) {
     e.printStackTrace();
   } catch (NoSuchMethodException e) {
     e.printStackTrace();
   } catch (IllegalArgumentException e) {
     e.printStackTrace();
   } catch (IllegalAccessException e) {
     e.printStackTrace();
   } catch (InvocationTargetException e) {
     e.printStackTrace();
   }
   return o;
 }
Пример #13
0
 /** @desc 初始化 */
 public void initMethods() {
   getMethods = new Hashtable<String, Method>();
   setMethods = new Hashtable<String, Method>();
   cls = obj.getClass();
   Method[] methods = cls.getMethods();
   // 定义正则表达式,从方法中过滤出getter / setter 函数.
   String gs = "get(\\w+)";
   Pattern getM = Pattern.compile(gs);
   String ss = "set(\\w+)";
   Pattern setM = Pattern.compile(ss);
   // 把方法中的"set" 或者 "get" 去掉
   String rapl = "$1";
   String param;
   for (int i = 0; i < methods.length; ++i) {
     Method m = methods[i];
     String methodName = m.getName();
     if (Pattern.matches(gs, methodName)) {
       param = getM.matcher(methodName).replaceAll(rapl).toLowerCase();
       getMethods.put(param, m);
     } else if (Pattern.matches(ss, methodName)) {
       param = setM.matcher(methodName).replaceAll(rapl).toLowerCase();
       setMethods.put(param, m);
     } else {
       // System.out.println(methodName + " 不是getter,setter方法!");
     }
   }
 }
Пример #14
0
 /**
  * 根据一个字段名和字段类型获取 Setter
  *
  * @param fieldName 字段名
  * @param paramType 字段类型
  * @return 方法
  * @throws NoSuchMethodException 没找到 Setter
  */
 public Method getSetter(String fieldName, Class<?> paramType) throws NoSuchMethodException {
   try {
     String setterName = "set" + Strings.capitalize(fieldName);
     try {
       return klass.getMethod(setterName, paramType);
     } catch (Throwable e) {
       try {
         return klass.getMethod(fieldName, paramType);
       } catch (Throwable e1) {
         Mirror<?> type = Mirror.me(paramType);
         for (Method method : klass.getMethods()) {
           if (method.getParameterTypes().length == 1)
             if (method.getName().equals(setterName) || method.getName().equals(fieldName)) {
               if (null == paramType || type.canCastToDirectly(method.getParameterTypes()[0]))
                 return method;
             }
         }
         // 还是没有? 会不会是包装类型啊?
         if (!paramType.isPrimitive()) {
           Class<?> p = unWrapper();
           if (null != p) return getSetter(fieldName, p);
         }
         throw new RuntimeException();
       }
     }
   } catch (Throwable e) {
     throw Lang.makeThrow(
         NoSuchMethodException.class,
         "Fail to find setter for [%s]->[%s(%s)]",
         klass.getName(),
         fieldName,
         paramType.getName());
   }
 }
Пример #15
0
 /** @return 所有静态方法 */
 public Method[] getStaticMethods() {
   List<Method> list = new LinkedList<Method>();
   for (Method m : klass.getMethods()) {
     if (Modifier.isStatic(m.getModifiers()) && Modifier.isPublic(m.getModifiers())) list.add(m);
   }
   return list.toArray(new Method[list.size()]);
 }
Пример #16
0
  private void scanBindings() throws IOException {
    for (Map.Entry<Key<?>, Binding<?>> e : globalInjector.getAllBindings().entrySet()) {
      Key<?> bindingKey = e.getKey();
      Binding<?> binding = e.getValue();
      TypeLiteral boundTypeLiteral = bindingKey.getTypeLiteral();
      Type boundType = boundTypeLiteral.getType();
      if (boundType instanceof Class) {
        final Class boundClass = (Class) boundType;
        for (Method method : boundClass.getMethods()) {
          if ((method.getModifiers() & Modifier.STATIC) == 0) {
            for (Annotation annotation : method.getAnnotations()) {
              if (annotation instanceof Path) {
                Path pathSpec = (Path) annotation;
                RouteSpec routeIn = Routes.parse(pathSpec.value(), true);
                endPointMethods.add(new EndPointMethod(routeIn, bindingKey, boundClass, method));
              }
            }
          }
        }

        if (MessageBodyReader.class.isAssignableFrom(boundClass)) {
          messageBodyReaders.add(0, (MessageBodyReader) globalInjector.getInstance(bindingKey));
        }
        if (MessageBodyWriter.class.isAssignableFrom(boundClass)) {
          messageBodyWriters.add(0, (MessageBodyWriter) globalInjector.getInstance(bindingKey));
        }
      }
    }
  }
  @Override
  public Object parseClass(Class<?> c, Object o, MainView view) {
    Method methods[] = c.getMethods();
    for (int i = 0; i < methods.length; i++) {
      try {
        if (methods[i].isAnnotationPresent(GetDatabase.class)) {
          if (o == null) {
            o = c.newInstance();
            Log.getLogger()
                .log(Level.INFO, "Initializing plugin with class: " + o.getClass().getSimpleName());
          }
          Log.getLogger().log(Level.INFO, "Setting DB...");
          Method panel = c.getMethod(methods[i].getName(), methods[i].getParameterTypes());
          if (panel.getReturnType() == void.class) {
            panel.invoke(o, DatabaseHandler.getInstance());
          } else {
            Log.getLogger().log(Level.SEVERE, "@GetDatabase invalid return type!");
          }

          break;
        }
      } catch (InstantiationException
          | IllegalAccessException
          | NoSuchMethodException
          | SecurityException
          | IllegalArgumentException
          | InvocationTargetException e) {
        Log.getLogger().log(Level.SEVERE, "Exception", e);
      }
    }

    return o;
  }
Пример #18
0
 /* ------------------------------------------------------------ */
 protected void init() {
   Method[] methods = _pojoClass.getMethods();
   for (int i = 0; i < methods.length; i++) {
     Method m = methods[i];
     if (!Modifier.isStatic(m.getModifiers()) && m.getDeclaringClass() != Object.class) {
       String name = m.getName();
       switch (m.getParameterTypes().length) {
         case 0:
           if (m.getReturnType() != null) {
             if (name.startsWith("is") && name.length() > 2)
               name = name.substring(2, 3).toLowerCase(Locale.ENGLISH) + name.substring(3);
             else if (name.startsWith("get") && name.length() > 3)
               name = name.substring(3, 4).toLowerCase(Locale.ENGLISH) + name.substring(4);
             else break;
             if (includeField(name, m)) addGetter(name, m);
           }
           break;
         case 1:
           if (name.startsWith("set") && name.length() > 3) {
             name = name.substring(3, 4).toLowerCase(Locale.ENGLISH) + name.substring(4);
             if (includeField(name, m)) addSetter(name, m);
           }
           break;
       }
     }
   }
 }
Пример #19
0
  private void initApiInfo() throws Exception {
    int apiCounter = 0;
    String[] beanNames = applicationContext.getBeanNamesForAnnotation(Controller.class);

    if (beanNames == null) {
      logger.info("No controller bean found. stop server and fix it.");
      throw new Exception("No controller bean found. stop server and fix it.");
    }

    Map<String, Object> checkMap = new HashMap<String, Object>();
    for (String beanName : beanNames) {
      logger.info("Controller bean found: " + beanName);
      Class<?> beanType = applicationContext.getType(beanName);

      Method[] methods = beanType.getMethods();
      for (Method method : methods) {
        if (method.getAnnotation(Api.class) != null
            && method.getAnnotation(RequestMapping.class) != null) {
          logger.info("Controller Api Method found: " + method.getName());
          if (checkMap.get(method.getName()) != null) {
            logger.info("Controller method name is duplicated! stop server and fix it.");
            throw new Exception("Controller method name is duplicated! stop server and fix it.");
          }
          checkMap.put(method.getName(), new Object());
          apiCounter++;
        }
      }
    }
    logger.info("Total {} api listed.", apiCounter);
    this.apiInfoCache = new ConcurrentHashMap<String, ApiInfo>();
  }
Пример #20
0
 // Simulates the compile-time binding of a method-name and a list of
 // parameter types. Whereas Class.getMethod(String, Class[])
 // looks for methods with the exact signature, this looks through all the
 // applicable public methods of the specified class, and selects the most specific.
 public static Method getMethod(Class clazz, String methodName, Class[] paramTypes)
     throws NoSuchMethodException {
   // Check the arguments are all non-null.
   if (clazz == null || methodName == null || paramTypes == null) {
     throw new IllegalArgumentException();
   }
   Method currentBestCandidate = null;
   // Iterate through the public methods of the class.
   Method[] candidates = clazz.getMethods();
   for (int i = 0; i < candidates.length; i++) {
     // We discard non-applicable methods immediately.
     if (methodApplicable(candidates[i], methodName, paramTypes)) {
       if (currentBestCandidate == null
           || methodMoreSpecific(candidates[i], currentBestCandidate)) {
         // candidates[i] is the new current best candidate.
         currentBestCandidate = candidates[i];
       } else if (!methodMoreSpecific(currentBestCandidate, candidates[i])) {
         // Neither method is more specific than the other.
         throw new NoSuchMethodException("Ambiguity");
       }
     }
   }
   // If we have a best candidate, that's the method to return.
   if (currentBestCandidate != null) {
     return currentBestCandidate;
   }
   // No such method found.
   throw new NoSuchMethodException("No applicable public method");
 }
  /**
   * @return a reference to the public static serializableInstance() method of clazz, if there is
   *     one; otherwise, returns null.
   */
  private Method serializableInstanceMethod(Class clazz) {
    Method[] methods = clazz.getMethods();

    for (Method method : methods) {
      if ("serializableInstance".equals(method.getName())) {
        Class[] parameterTypes = method.getParameterTypes();

        if (!(parameterTypes.length == 0)) {
          continue;
        }

        if (!(Modifier.isStatic(method.getModifiers()))) {
          continue;
        }

        if (Modifier.isAbstract(method.getModifiers())) {
          continue;
        }

        return method;
      }
    }

    return null;
  }
Пример #22
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()
            + ".");
  }
Пример #23
0
 private void loadClass() throws SQLException {
   Class<?> javaClass = ClassUtils.loadUserClass(className);
   Method[] methods = javaClass.getMethods();
   ObjectArray<JavaMethod> list = ObjectArray.newInstance();
   for (int i = 0; i < methods.length; i++) {
     Method m = methods[i];
     if (!Modifier.isStatic(m.getModifiers())) {
       continue;
     }
     if (m.getName().equals(methodName) || getMethodSignature(m).equals(methodName)) {
       JavaMethod javaMethod = new JavaMethod(m, i);
       for (JavaMethod old : list) {
         if (old.getParameterCount() == javaMethod.getParameterCount()) {
           throw Message.getSQLException(
               ErrorCode.METHODS_MUST_HAVE_DIFFERENT_PARAMETER_COUNTS_2,
               old.toString(),
               javaMethod.toString());
         }
       }
       list.add(javaMethod);
     }
   }
   if (list.size() == 0) {
     throw Message.getSQLException(
         ErrorCode.PUBLIC_STATIC_JAVA_METHOD_NOT_FOUND_1, methodName + " (" + className + ")");
   }
   javaMethods = new JavaMethod[list.size()];
   list.toArray(javaMethods);
   // Sort elements. Methods with a variable number of arguments must be at
   // the end. Reason: there could be one method without parameters and one
   // with a variable number. The one without parameters needs to be used
   // if no parameters are given.
   Arrays.sort(javaMethods);
 }
  private <T> T generateProxy(
      final Class<T> proxyInterface,
      final RingBuffer<ProxyMethodInvocation> ringBuffer,
      final Map<Method, Invoker> methodToInvokerMap,
      final OverflowStrategy overflowStrategy,
      final ArgumentHolderGenerator argumentHolderGenerator) {
    final CtClass ctClass =
        makeClass(
            classPool, "_proxy" + proxyInterface.getSimpleName() + '_' + getUniqueIdentifier());

    addInterface(ctClass, proxyInterface, classPool);
    makePublicFinal(ctClass);

    createFields(methodToInvokerMap, ctClass);
    createConstructor(ctClass);

    for (final Method method : proxyInterface.getMethods()) {
      createRingBufferPublisherMethod(
          ctClass,
          method,
          methodToInvokerMap.get(method),
          overflowStrategy,
          argumentHolderGenerator);
    }

    return instantiateProxy(ctClass, ringBuffer);
  }
Пример #25
0
  /**
   * This method retrieves all the values accessible through a getter ( <code>getX()</code> method)
   * in order to build the corresponding set of {@link Objective}s. At the opposite of {@link
   * #createFromGetters(Class)}, an additional filter is used: we build an {@link Objective} for
   * each getter which does not correspond to a setter (<code>setX()</code> method with the same
   * <code>X</code> than the getter). This method is adapted for {@link Solution} implementations
   * which provide setters only for their fundamental values (e.g. the path of a TSP {@link
   * Solution}) and use getters only for the computed values (e.g. the length of such a path).<br>
   * <br>
   * Notice that, if all the relevant getters are not present, the corresponding {@link Objective}s
   * will not be retrieved. On the opposite, any additional getter which does not correspond to a
   * relevant {@link Objective} will be mistakenly retrieved. So be sure that the relevant elements
   * (and only these ones) have their getter (and no setter). Otherwise, you should use a different
   * method or generate the {@link Objective}s manually.
   *
   * @param solutionClass the {@link Solution} class to analyze
   * @return the set of {@link Objective}s retrieved from this class
   */
  public <Solution> Collection<Objective<Solution, ?>> createFromGettersWithoutSetters(
      Class<Solution> solutionClass) {
    Map<String, Method> getters = new HashMap<>();
    Map<String, Method> setters = new HashMap<>();
    for (Method method : solutionClass.getMethods()) {
      if (isGetter(method)) {
        String name = method.getName().substring(3);
        getters.put(name, method);
      } else if (isSetter(method)) {
        String name = method.getName().substring(3);
        setters.put(name, method);
      } else {
        // not a getter/setter, ignore it
      }
    }

    getters.keySet().removeAll(setters.keySet());

    Collection<Objective<Solution, ?>> objectives = new LinkedList<>();
    for (Entry<String, Method> entry : getters.entrySet()) {
      String name = entry.getKey();
      Method getter = entry.getValue();
      objectives.add(createObjectiveOn(solutionClass, getter, name, getter.getReturnType()));
    }
    return objectives;
  }
Пример #26
0
  public static Set<Method> findSetterMethods(
      Class<?> clazz, String name, boolean allowBuilderPattern) {
    Set<Method> candidates = new LinkedHashSet<Method>();

    // Build the method name.
    name = "set" + ObjectHelper.capitalize(name);
    while (clazz != Object.class) {
      // Since Object.class.isInstance all the objects,
      // here we just make sure it will be add to the bottom of the set.
      Method objectSetMethod = null;
      Method[] methods = clazz.getMethods();
      for (Method method : methods) {
        if (method.getName().equals(name) && isSetter(method, allowBuilderPattern)) {
          Class<?> params[] = method.getParameterTypes();
          if (params[0].equals(Object.class)) {
            objectSetMethod = method;
          } else {
            candidates.add(method);
          }
        }
      }
      if (objectSetMethod != null) {
        candidates.add(objectSetMethod);
      }
      clazz = clazz.getSuperclass();
    }
    return candidates;
  }
 @Override
 public Method findMethod(Object target, String methodName) {
   Class<? extends Object> targetClass = target.getClass();
   String key = targetClass.getName() + "#" + methodName;
   LOG.info("findMethod() trying to find {}", key);
   Method method = cache.get(key);
   if (method != null) {
     return method == NULL_METHOD ? null : method;
   } // if
   for (Method m : targetClass.getMethods()) {
     if (m.getName().equals(methodName)) {
       LinkAction linkAction = m.getAnnotation(LinkAction.class);
       LOG.info(
           "findMethod() linkAction={}  method.getReturnType()={}", linkAction, m.getReturnType());
       if (!TargetDescriptor.class.equals(m.getReturnType())) {
         linkAction = null;
       } // if
       LOG.debug("findMethod() linkAction={}", linkAction);
       if (linkAction != null) {
         method = m;
       } // if
     } // if
   } // for
   cache.put(key, method == null ? NULL_METHOD : method);
   return method;
 } // findMethod()
Пример #28
0
  private void resolveFields() {
    for (Method method : objectType.getMethods()) {
      if ((method.getModifiers() & Modifier.STATIC) != 0) {
        continue;
      }

      String fieldName = null;
      if (method.getName().startsWith("get")) {
        if (method.getName().equals("getId") || method.getName().length() <= 3) {
          continue;
        }
        // Found a field!
        fieldName = getFieldName(method.getName());
      } else if (method.getName().startsWith("is")) {
        if (method.getName().length() <= 2) {
          continue;
        }
        // Found a field!
        fieldName = getFieldName(method.getName());
      }

      if (fieldName != null) {
        fieldTypeMap.put(fieldName, method.getReturnType());
      }
    }

    int index = 0;
    for (String fieldName : fieldTypeMap.keySet()) {
      fieldIndexMap.put(fieldName, index++);
    }
  }
Пример #29
0
  /**
   * 遍历项目导入所有的Router
   *
   * @throws UnsupportedEncodingException
   * @throws RouterException
   */
  public static void loadRouter() throws RouterException {
    try {
      List<String> classNames = PackageUtil.getClassName("model.controller");
      for (String className : classNames) {
        System.out.println(classNames);
        Class clazz = Class.forName(className);
        if (!clazz.isAnnotationPresent(Controller.class)) // 只有有Controller注解的类才处理
        continue;
        /** 遍历类下的方法 */
        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
          if (!method.isAnnotationPresent(RequestMapping.class)) // 只有有RequestMapping的方法才生成router
          continue;

          Annotation annotation = method.getAnnotation(RequestMapping.class);
          Action action = new Action();
          action.setActionPath(((RequestMapping) annotation).value());
          action.setController(clazz.newInstance());
          action.setMethod(method);
          addRouter(action);
        }
      }
    } catch (ClassNotFoundException e) {
      throw (new RouterException(e));
    } catch (InstantiationException e) {
      throw (new RouterException(e));
    } catch (IllegalAccessException e) {
      throw (new RouterException(e));
    } catch (UnsupportedEncodingException e) {
      // TODO Auto-generated catch block
      throw (new RouterException(e));
    }
  }
 private void inspect() {
   managerModCount = manager.getModCount();
   // first global, then type level, then method level
   // but later one can override pre (for same annotation)
   List<Annotation> typeLevel = new ArrayList<Annotation>();
   Class<?> serviceType = serviceClass;
   while (serviceType != null) {
     for (Annotation ann : serviceType.getAnnotations()) {
       if (ann.annotationType().isAnnotationPresent(AcServiceIntercepted.class)) {
         putOrAppendAnnotation(typeLevel, ann);
       }
     }
     Class<?> theType = serviceType;
     serviceType = null;
     for (Class<?> superInf : theType.getInterfaces()) {
       if (AcService.class.isAssignableFrom(superInf)) {
         serviceType = superInf;
         break;
       }
     }
   }
   for (Method method : serviceClass.getMethods()) {
     List<Annotation> annList = new ArrayList<Annotation>(typeLevel);
     for (Annotation ann : method.getAnnotations()) {
       if (ann.annotationType().isAnnotationPresent(AcServiceIntercepted.class)) {
         putOrAppendAnnotation(annList, ann);
       }
     }
     methodAnnotationList.put(method, annList);
     setupRuntimeInterceptorList(method);
   }
 }