Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2013 Tatsuhiro Tsujikawa
   *
   * Permission is hereby granted, free of charge, to any person
   * obtaining a copy of this software and associated documentation
   * files (the "Software"), to deal in the Software without
   * restriction, including without limitation the rights to use, copy,
   * modify, merge, publish, distribute, sublicense, and/or sell copies
   * of the Software, and to permit persons to whom the Software is
  * furnished to do so, subject to the following conditions:
  *
  * The above copyright notice and this permission notice shall be
  * included in all copies or substantial portions of the Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  * SOFTWARE.
  */
 package net.sourceforge.argparse4j.impl.type;
 
 

This implementation converts String value into given type using type's valueOf(java.lang.String) static method or its constructor.

 
 public class ReflectArgumentType<T> implements ArgumentType<T> {
 
     private Class<T> type_;

    

Creates ReflectArgumentType object with given type.

This object first tries to convert given String using valueOf(java.lang.String) static method of given type. If that failed, then use constructor of given type for conversion. valueOf() method and/or constructor must be declared as public. Otherwise, they cannot be invoked. The constructor of type must accept 1 String argument.

If error occurred inside the valueOf static method or constructor, net.sourceforge.argparse4j.inf.ArgumentParserException will be thrown. If error occurred in other locations, subclass of java.lang.RuntimeException will be thrown.

This object works with enums as well. The enums in its nature have limited number of members. In convert(net.sourceforge.argparse4j.inf.ArgumentParser,net.sourceforge.argparse4j.inf.Argument,java.lang.String), string value will be converted to one of them. If it cannot be converted, convert(net.sourceforge.argparse4j.inf.ArgumentParser,net.sourceforge.argparse4j.inf.Argument,java.lang.String) will throw net.sourceforge.argparse4j.inf.ArgumentParserException. This means it already act like a net.sourceforge.argparse4j.inf.Argument.choices(java.lang.Object[]).

Parameters:
type The type String value should be converted to.
 
     public ReflectArgumentType(Class<T> type) {
          = type;
     }
 
     @Override
     public T convert(ArgumentParser parserArgument argString value)
             throws ArgumentParserException {
         // Handle enums separately. Enum.valueOf() is very convenient here.
         // It somehow can access private enum values, where normally T.valueOf()
         // cannot without setAccessible(true).
         if (.isEnum()) {
             try {
                 return (T) Enum.valueOf((Class<Enum>) value);
             } catch (IllegalArgumentException e) {
                 throwArgumentParserException(parserargvaluee);
             }
         }
         Method m = null;
         try {
             m = .getMethod("valueOf"String.class);
         } catch (NoSuchMethodException e) {
             // If no valueOf static method found, try constructor.
             return convertUsingConstructor(parserargvalue);
        } catch (SecurityException e) {
            handleInstatiationError(e);
        }
        // Only interested in static valueOf method.
        if (!Modifier.isStatic(m.getModifiers())
                || !.isAssignableFrom(m.getReturnType())) {
            return convertUsingConstructor(parserargvalue);
        }
        Object obj = null;
        try {
            obj = m.invoke(nullvalue);
        } catch (IllegalAccessException e) {
            return convertUsingConstructor(parserargvalue);
        } catch (IllegalArgumentException e) {
            handleInstatiationError(e);
        } catch (InvocationTargetException e) {
            throwArgumentParserException(parserargvalue,
                    e.getCause() == null ? e : e.getCause());
        }
        return (T) obj;
    }
    private T convertUsingConstructor(ArgumentParser parserArgument arg,
            String valuethrows ArgumentParserException {
        T obj = null;
        try {
            obj = .getConstructor(String.class).newInstance(value);
        } catch (InstantiationException e) {
            handleInstatiationError(e);
        } catch (IllegalAccessException e) {
            handleInstatiationError(e);
        } catch (InvocationTargetException e) {
            throwArgumentParserException(parserargvalue,
                    e.getCause() == null ? e : e.getCause());
        } catch (NoSuchMethodException e) {
            handleInstatiationError(e);
        }
        return obj;
    }
    private void throwArgumentParserException(ArgumentParser parser,
            Argument argString valueThrowable t)
            throws ArgumentParserException {
        throw new ArgumentParserException(String.format(
                "could not convert '%s' to %s (%s)"value,
                .getSimpleName(), t.getMessage()), tparserarg);
    }
    private void handleInstatiationError(Exception e) {
        throw new IllegalArgumentException("reflect type conversion error"e);
    }
New to GrepCode? Check out our FAQ X