Example #1
0
  @SuppressWarnings("unchecked")
  public static <T> JsapResultsWithObject<T> constructObject(
      Class<T> clazz, String[] rawArguments, String mainHelp, Parameter[] otherParameters)
      throws JSAPException, IOException, IllegalArgumentException, ReflectiveOperationException {
    Constructor<T> constructor = null;
    for (Constructor<?> constr : clazz.getConstructors()) {
      boolean annotationPresent = constr.isAnnotationPresent(CommandLine.class);
      if (annotationPresent) {
        constructor = (Constructor<T>) constr;
        break;
      }
    }
    if (constructor == null)
      throw new IllegalAccessError(
          "Class " + clazz + " must have a constructor annotated with @CommandLine");

    String[] argNames = constructor.getAnnotation(CommandLine.class).argNames();
    if (argNames.length != constructor.getParameterCount())
      throw new IllegalAnnotationException(
          "Annotation @CommandLine argNames are out of sync with the constructor arguments.");

    boolean[] isSerializedFile = new boolean[argNames.length];

    SimpleJSAP jsap = new SimpleJSAP(clazz.getName(), mainHelp, otherParameters);
    int i = 0;
    for (java.lang.reflect.Parameter x : constructor.getParameters()) {
      Parameter option;
      if (x.getType().equals(boolean.class)) {
        isSerializedFile[i] = false;
        option =
            new Switch(
                argNames[i],
                JSAP.NO_SHORTFLAG,
                argNames[i],
                "Set the value of " + argNames[i] + " for " + clazz.getSimpleName() + " as true.");
      } else {
        StringParser parser;
        String help;
        try {
          parser = getParserFor(x.getType());
          isSerializedFile[i] = false;
          help = "The " + x.getType().getSimpleName() + " value of " + argNames[i];
        } catch (NoJSAPParserForThisTypeException e) {
          parser = JSAP.STRING_PARSER;
          isSerializedFile[i] = true;
          help =
              "A serialized " + x.getType().getSimpleName() + " file to initialize " + argNames[i];
        }
        option = new UnflaggedOption(argNames[i], parser, JSAP.REQUIRED, help);
      }

      jsap.registerParameter(option);

      i++;
    }

    JSAPResult args = jsap.parse(rawArguments);
    if (jsap.messagePrinted()) System.exit(1);

    LOGGER.info("Initializing...");
    Object[] arguments = new Object[argNames.length];
    i = 0;
    for (String argName : argNames) {
      if (isSerializedFile[i]) arguments[i] = SerializationUtils.read(args.getString(argName));
      else arguments[i] = args.getObject(argName);
      i++;
    }
    T object = constructor.newInstance(arguments);
    LOGGER.info("Ready.");

    return new JsapResultsWithObject<T>(args, object);
  }