Ejemplo n.º 1
0
  /**
   * Search a wiring method in the specified class.
   *
   * @param cl the class where to find the method
   * @param methodName the method to be searched
   * @return the requested method, if it fully conforms to the definition of the wiring methods.
   */
  private static Method getMethod(Class cl, String methodName)
      throws NoSuchMethodException, ClassNotFoundException {

    // Search methods
    Method[] methods = cl.getMethods();
    ArrayList<Method> list = new ArrayList<Method>();
    for (Method m : methods) {
      if (m.getName().equals(methodName)) {
        list.add(m);
      }
    }

    if (list.size() == 0) {
      throw new NoSuchMethodException(
          "No method " + methodName + " in class " + cl.getSimpleName());
    } else if (list.size() > 1) {
      throw new NoSuchMethodException(
          "Multiple methods called " + methodName + " in class " + cl.getSimpleName());
    }

    // Found a single method with the right name; check if
    // it is a setter.
    final Class graphClass = Class.forName("peersim.graph.Graph");
    final Class randomClass = Class.forName("java.util.Random");
    Method method = list.get(0);
    Class[] pars = method.getParameterTypes();
    if (pars.length < 1 || !pars[0].isAssignableFrom(graphClass))
      throw new NoSuchMethodException(
          method.getName()
              + " of class "
              + cl.getSimpleName()
              + " is not a valid graph wiring method,"
              + " it has to have peersim.graph.Graph as first argument type");
    for (int i = 1; i < pars.length; ++i)
      if (!(pars[i] == int.class
          || pars[i] == long.class
          || pars[i] == double.class
          || (i == pars.length - 1 && pars[i].isAssignableFrom(randomClass))))
        throw new NoSuchMethodException(
            method.getName()
                + " of class "
                + cl.getSimpleName()
                + " is not a valid graph wiring method");

    if (method.toString().indexOf("static") < 0)
      throw new NoSuchMethodException(
          method.getName()
              + " of class "
              + cl.getSimpleName()
              + " is not a valid graph wiring method; it is not static");

    return method;
  }