Exemple #1
0
  static CachedMethod[] getMethods(Kryo kryo, Class type) {
    CachedMethod[] cachedMethods = methodCache.get(type);
    if (cachedMethods != null) {
      return cachedMethods;
    }

    ArrayList<Method> allMethods = new ArrayList();
    Class nextClass = type;
    while ((nextClass != null) && (nextClass != Object.class)) {
      Collections.addAll(allMethods, nextClass.getDeclaredMethods());
      nextClass = nextClass.getSuperclass();
    }
    PriorityQueue<Method> methods =
        new PriorityQueue(
            Math.max(1, allMethods.size()),
            new Comparator<Method>() {
              @Override
              public int compare(Method o1, Method o2) {
                // Methods are sorted so they can be represented as an index.
                int diff = o1.getName().compareTo(o2.getName());
                if (diff != 0) {
                  return diff;
                }
                Class[] argTypes1 = o1.getParameterTypes();
                Class[] argTypes2 = o2.getParameterTypes();
                if (argTypes1.length > argTypes2.length) {
                  return 1;
                }
                if (argTypes1.length < argTypes2.length) {
                  return -1;
                }
                for (int i = 0; i < argTypes1.length; i++) {
                  diff = argTypes1[i].getName().compareTo(argTypes2[i].getName());
                  if (diff != 0) {
                    return diff;
                  }
                }
                throw new RuntimeException("Two methods with same signature!"); // Impossible.
              }
            });
    for (int i = 0, n = allMethods.size(); i < n; i++) {
      Method method = allMethods.get(i);
      int modifiers = method.getModifiers();
      if (Modifier.isStatic(modifiers)) {
        continue;
      }
      if (Modifier.isPrivate(modifiers)) {
        continue;
      }
      if (method.isSynthetic()) {
        continue;
      }
      methods.add(method);
    }

    int n = methods.size();
    cachedMethods = new CachedMethod[n];
    for (int i = 0; i < n; i++) {
      CachedMethod cachedMethod = new CachedMethod();
      cachedMethod.method = methods.poll();

      // Store the serializer for each final parameter.
      Class[] parameterTypes = cachedMethod.method.getParameterTypes();
      cachedMethod.serializers = new Serializer[parameterTypes.length];
      for (int ii = 0, nn = parameterTypes.length; ii < nn; ii++) {
        if (kryo.isFinal(parameterTypes[ii])) {
          cachedMethod.serializers[ii] = kryo.getSerializer(parameterTypes[ii]);
        }
      }

      cachedMethods[i] = cachedMethod;
    }
    methodCache.put(type, cachedMethods);
    return cachedMethods;
  }