Example usage for java.lang Character valueOf

List of usage examples for java.lang Character valueOf

Introduction

In this page you can find the example usage for java.lang Character valueOf.

Prototype

@HotSpotIntrinsicCandidate
public static Character valueOf(char c) 

Source Link

Document

Returns a Character instance representing the specified char value.

Usage

From source file:org.plasma.text.lang3gl.java.DefaultFactory.java

public DefaultFactory(Lang3GLContext context) {
    this.context = context;
    this.reservedJavaCharToLiteralMap.put(Character.valueOf('+'), "_plus_");
    this.reservedJavaCharToLiteralMap.put(Character.valueOf('-'), "_minus_");
    this.reservedJavaCharToLiteralMap.put(Character.valueOf('/'), "_div_");
    this.reservedJavaCharToLiteralMap.put(Character.valueOf('*'), "_mult_");
    this.reservedJavaCharToLiteralMap.put(Character.valueOf('%'), "_mod_");
    this.reservedJavaCharToLiteralMap.put(Character.valueOf('('), "_rp_");
    this.reservedJavaCharToLiteralMap.put(Character.valueOf(')'), "_lp_");
    this.reservedJavaCharToLiteralMap.put(Character.valueOf('('), "_rb_");
    this.reservedJavaCharToLiteralMap.put(Character.valueOf(')'), "_lb_");
}

From source file:hr.fer.spocc.automaton.fsm.DefaultNondeterministicFiniteAutomatonTest.java

@Test
public void testAddTransition1() {
    NondeterministicFiniteAutomaton<Character> nfa = createNfa();

    // dodaj dva stanja s id-evima 1 i 2
    nfa.addState(new State(1, false));
    nfa.addState(new State(2, false));

    // dodaj prijelaz izmedju ta dva stanja
    nfa.addTransition(1, 2, 'x');

    // vrati kolekciju svih prijelaza
    Collection<Transition<Character>> transitions = nfa.getTransitions();

    // testiraj da li kolekcija sadrzi tocno jedan prijelaz
    Assert.assertEquals(1, transitions.size());

    // testiraj da li kolekcija sadrzi pravi prijelaz
    Transition<Character>[] tranArray = toTransitionArray(transitions);
    Transition<Character> singleTransition = tranArray[0];
    State state1 = nfa.getState(1), state2 = nfa.getState(2);
    // assertSame ti testira da li se radi o istom objektu
    // (ekvivalentno sa operatorom ==)
    Assert.assertSame(state1, singleTransition.getFrom());
    Assert.assertSame(state2, singleTransition.getTo());
    // assertEquals testira da li su objekti (kopije) jednaki
    // a to se ustanovljuje pozivom .equals() metode
    Assert.assertEquals(Character.valueOf('x'), // mogli smo i castati 
            singleTransition.getSymbol());

    // Character je objekt koji sadrzi char
    // on moze biti null (to je nama epsilon prijelaz onda)

    // jos jednom test da li je prijelaz isti (na drugi nacin)
    // ovo za rezliku od proslog usporedjuje da li je prijelaz
    // jednak, a ne da li je isti (da li ima reference na ista stanja)
    checkTransition(nfa, 1, 2, 'x', singleTransition);
}

From source file:org.eobjects.analyzer.util.convert.StandardTypeConverter.java

@Override
public Object fromString(Class<?> type, String str) {
    if (ReflectionUtils.isString(type)) {
        return str;
    }/*from w w  w . j  a v a  2s  .c  o m*/
    if (ReflectionUtils.isBoolean(type)) {
        return Boolean.valueOf(str);
    }
    if (ReflectionUtils.isCharacter(type)) {
        return Character.valueOf(str.charAt(0));
    }
    if (ReflectionUtils.isInteger(type)) {
        return Integer.valueOf(str);
    }
    if (ReflectionUtils.isLong(type)) {
        return Long.valueOf(str);
    }
    if (ReflectionUtils.isByte(type)) {
        return Byte.valueOf(str);
    }
    if (ReflectionUtils.isShort(type)) {
        return Short.valueOf(str);
    }
    if (ReflectionUtils.isDouble(type)) {
        return Double.valueOf(str);
    }
    if (ReflectionUtils.isFloat(type)) {
        return Float.valueOf(str);
    }
    if (ReflectionUtils.is(type, Class.class)) {
        try {
            return Class.forName(str);
        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException("Class not found: " + str, e);
        }
    }
    if (type.isEnum()) {
        try {
            Object[] enumConstants = type.getEnumConstants();

            // first look for enum constant matches
            Method nameMethod = Enum.class.getMethod("name");
            for (Object e : enumConstants) {
                String name = (String) nameMethod.invoke(e);
                if (name.equals(str)) {
                    return e;
                }
            }

            // check for aliased enums
            for (Object e : enumConstants) {
                String name = (String) nameMethod.invoke(e);
                Field field = type.getField(name);
                Alias alias = ReflectionUtils.getAnnotation(field, Alias.class);
                if (alias != null) {
                    String[] aliasValues = alias.value();
                    for (String aliasValue : aliasValues) {
                        if (aliasValue.equals(str)) {
                            return e;
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new IllegalStateException("Unexpected error occurred while examining enum", e);
        }
        throw new IllegalArgumentException("No such enum '" + str + "' in enum class: " + type.getName());
    }
    if (ReflectionUtils.isDate(type)) {
        return toDate(str);
    }
    if (ReflectionUtils.is(type, File.class)) {
        return new File(str.replace('\\', File.separatorChar));
    }
    if (ReflectionUtils.is(type, Calendar.class)) {
        Date date = toDate(str);
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        return c;
    }
    if (ReflectionUtils.is(type, Pattern.class)) {
        try {
            return Pattern.compile(str);
        } catch (PatternSyntaxException e) {
            throw new IllegalArgumentException("Invalid regular expression syntax in '" + str + "'.", e);
        }
    }
    if (ReflectionUtils.is(type, java.sql.Date.class)) {
        Date date = toDate(str);
        return new java.sql.Date(date.getTime());
    }
    if (ReflectionUtils.isNumber(type)) {
        return ConvertToNumberTransformer.transformValue(str);
    }
    if (ReflectionUtils.is(type, Serializable.class)) {
        logger.warn("fromString(...): No built-in handling of type: {}, using deserialization", type.getName());
        byte[] bytes = (byte[]) parentConverter.fromString(byte[].class, str);
        ChangeAwareObjectInputStream objectInputStream = null;
        try {
            objectInputStream = new ChangeAwareObjectInputStream(new ByteArrayInputStream(bytes));
            objectInputStream.addClassLoader(type.getClassLoader());
            Object obj = objectInputStream.readObject();
            return obj;
        } catch (Exception e) {
            throw new IllegalStateException("Could not deserialize to " + type + ".", e);
        } finally {
            FileHelper.safeClose(objectInputStream);
        }
    }

    throw new IllegalArgumentException("Could not convert to type: " + type.getName());
}

From source file:net.pandoragames.far.ui.SimpleFileNamePattern.java

/**
 * Protected constructor for inheriting classes.
 *///www .ja v a  2 s .c  o  m
protected SimpleFileNamePattern() {
    for (char character : forbiddenCharactersInSimplePattern) {
        forbiddenCharacters.add(Character.valueOf(character));
    }
    forbiddenCharacters.add(Character.valueOf(System.getProperty("file.separator").charAt(0)));
    forbiddenCharacters.add(Character.valueOf(System.getProperty("path.separator").charAt(0)));
    for (char character : toBeEscapedInSimplePattern) {
        toBeEscaped.add(Character.valueOf(character));
    }
}

From source file:com.magnet.android.mms.request.GenericResponseParserPrimitiveTest.java

@SmallTest
public void testStringResponse() throws MobileException, IOException {
    GenericResponseParser<String> parser = new GenericResponseParser<String>(String.class);
    String response = "\"Whatever is the deal\"";

    String result = (String) parser.parseResponse(response.getBytes());
    assertEquals("Whatever is the deal", result);

    result = (String) parser.parseResponse((byte[]) null);
    assertEquals(null, result);/* w ww .ja v  a  2s .  co m*/

    result = (String) parser.parseResponse("\"\"".getBytes());
    assertEquals("", result);

    GenericResponseParser<Character> cparser = new GenericResponseParser<Character>(char.class);
    char cresponse = 'p';

    try {
        Character cresult = (Character) cparser.parseResponse(String.valueOf(cresponse).getBytes("UTF-8"));
        assertEquals(Character.valueOf(cresponse), cresult);
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.workday.autoparse.json.demo.JsonParserTest.java

private void testParse(String fileName) throws Exception {
    TestObject testObject = (TestObject) parser.parseJsonStream(getInputStream(fileName));
    assertNotNull("testObject", testObject);

    assertEquals("testObject.discriminationValue", "testObject", testObject.discriminationValue);
    assertEquals("testObject.superDiscriminationValue", "testObject", testObject.superDiscriminationValue);

    // Basic Types
    assertTrue("testObject.myBoolean", testObject.myBoolean);
    assertEquals("testObject.myByte", (byte) 65, testObject.myByte);
    assertEquals("testObject.myChar", 'c', testObject.myChar);
    assertEquals("testObject.myDouble", 12.34, testObject.myDouble, ERROR);
    assertEquals("testObject.myFloat", 123.45f, testObject.myFloat, ERROR);
    assertEquals("testObject.myInt", 12, testObject.myInt);
    assertEquals("testObject.myLong", 123456, testObject.myLong);
    assertEquals("testObject.myShort", 17, testObject.myShort);

    assertTrue("testObject.myBoxedBoolean", testObject.myBoxedBoolean);
    assertEquals("testObject.myBoxedByte", Byte.valueOf("63"), testObject.myBoxedByte);
    assertEquals("testObject.myBoxedChar", Character.valueOf('d'), testObject.myBoxedChar);
    assertEquals("testObject.myBoxedDouble", Double.valueOf("12.345"), testObject.myBoxedDouble);
    assertEquals("testObject.myBoxedFloat", Float.valueOf("123.456"), testObject.myBoxedFloat);
    assertEquals("testObject.myBoxedInt", Integer.valueOf("123"), testObject.myBoxedInt);
    assertEquals("testObject.myBoxedLong", Long.valueOf(1234567), testObject.myBoxedLong);
    assertEquals("testObject.myBoxedShort", new Short("18"), testObject.myBoxedShort);

    assertEquals("testObject.myString", "hello", testObject.myString);
    assertEquals("testObject.myBigDecimal", new BigDecimal("123456789.0123456789"), testObject.myBigDecimal);
    assertEquals("testObject.myBigInteger", new BigInteger("1234567891011"), testObject.myBigInteger);
    assertEquals("testObject.overriddenThing", 123, testObject.overriddenThing);
    assertNull("testObject.superOverriddenThing", testObject.superOverriddenThing);

    // Maps//www. ja  va 2  s .  c  o  m
    assertNotNull("testObject.myStringMap", testObject.myStringMap);
    assertEquals("testObject.myStringMap.size", 2, testObject.myStringMap.size());
    assertEquals("testObject.myStringMap[key1]", "value1", testObject.myStringMap.get("key1"));
    assertEquals("testObject.myStringMap[key2]", "value2", testObject.myStringMap.get("key2"));

    assertNotNull("testObject.myTestObjectMap", testObject.myTestObjectMap);
    assertEquals("testObject.myTestObjectMap.size", 2, testObject.myTestObjectMap.size());
    assertEquals("testObject.myTestObjectMap[key1]", new SimpleTestObject("post-parse:string 1"),
            testObject.myTestObjectMap.get("key1"));
    assertEquals("testObject.myTestObjectMap[key2]", new SimpleTestObject("post-parse:string 2"),
            testObject.myTestObjectMap.get("key2"));

    assertNotNull("testObject.myInterfaceMap", testObject.myInterfaceMap);
    assertEquals("testObject.myInterfaceMap.size", 2, testObject.myInterfaceMap.size());
    assertEquals("testObject.myInterfaceMap[key1]", new TestObject.InnerTestObject("string 1"),
            testObject.myInterfaceMap.get("key1"));
    assertEquals("testObject.myInterfaceMap[key2]", new TestObject.InnerTestObject("string 2"),
            testObject.myInterfaceMap.get("key2"));

    assertNotNull("testObject.myObjectMap", testObject.myObjectMap);
    assertEquals("testObject.myObjectMap.size", 2, testObject.myTestObjectMap.size());
    assertEquals("testObject.myObjectMap[key1]",
            new SimpleTestObject("post-parse:string 1", "simpleTestObject"),
            testObject.myObjectMap.get("key1"));
    assertEquals("testObject.myObjectMap[key2]", "25", testObject.myObjectMap.get("key2"));

    // Collections
    assertEquals("testObject.myBooleanCollection", CollectionUtils.newHashSet(true, false, true),
            testObject.myBooleanCollection);
    assertEquals("testObject.myByteCollection", CollectionUtils.newHashSet((byte) 63, (byte) 64),
            testObject.myByteCollection);
    assertEquals("testObject.myCharCollection", new LinkedHashSet<>(CollectionUtils.newArrayList('d', 'e')),
            testObject.myCharCollection);
    assertEquals("testObject.myDoubleCollection",
            new LinkedList<>(CollectionUtils.newArrayList(12.345, 13.345)), testObject.myDoubleCollection);
    assertEquals("testObject.myFloatCollection", CollectionUtils.newArrayList(123.456f, 234.56f),
            testObject.myFloatCollection);
    assertEquals("testObject.myIntCollection", CollectionUtils.newArrayList(123, 456),
            testObject.myIntCollection);
    assertEquals("testObject.myLongCollection", CollectionUtils.newArrayList(1234567L, 2345678L),
            testObject.myLongCollection);
    assertEquals("testObject.myShortCollection", CollectionUtils.newArrayList((short) 18, (short) 19),
            testObject.myShortCollection);
    assertEquals("testObject.myStringCollection", CollectionUtils.newArrayList("hello", "there"),
            testObject.myStringCollection);
    assertEquals("testObject.myBigDecimalCollection", CollectionUtils
            .newArrayList(new BigDecimal("123456789.0123456789"), new BigDecimal("23456789.0123456789")),
            testObject.myBigDecimalCollection);
    assertEquals("testObject.myBigIntegerCollection",
            CollectionUtils.newArrayList(new BigInteger("1234567891011"), new BigInteger("234567891011")),
            testObject.myBigIntegerCollection);

    // Custom Objects
    SimpleTestObject singularChild = testObject.mySingularChild;
    assertNotNull("testObject.mySingularChild", singularChild);
    assertEquals("testObject.mySingularChild.myString", "post-parse:a singular child", singularChild.myString);
    assertTrue("testObject.mySingularChildByInterface instanceOf InnerTestObject",
            testObject.mySingularChildByInterface instanceof TestObject.InnerTestObject);
    assertEquals("testObject.mySingularChildByInterface.string", "an object",
            ((TestObject.InnerTestObject) (testObject.mySingularChildByInterface)).string);

    assertEquals("testObject.myInnerObject", new TestObject.InnerTestObject("an InnerTestObject"),
            testObject.myInnerObject);

    List<SimpleTestObject> list = testObject.myList;
    assertNotNull("testObject.myList", list);
    assertEquals("testObject.myList.size()", 2, list.size());
    assertEquals("testObject.myList[0].myString", "post-parse:list child 0", list.get(0).myString);
    assertEquals("testObject.myList[1].myString", "post-parse:list child 1", list.get(1).myString);

    assertNotNull("testObject.myListByInterface", testObject.myListByInterface);
    assertEquals("testObject.myListByInterface", 2, testObject.myListByInterface.size());
    assertTrue("testObject.myListByInterface[0] instanceOf InnerTestObject",
            testObject.myListByInterface.get(0) instanceof TestObject.InnerTestObject);
    assertEquals("testObject.myListByInterface[0]", "object 0",
            ((TestObject.InnerTestObject) (testObject.myListByInterface.get(0))).string);
    assertTrue("testObject.myListByInterface[1] instanceOf InnerTestObject",
            testObject.myListByInterface.get(1) instanceof TestObject.InnerTestObject);
    assertEquals("testObject.myListByInterface[1]", "object 1",
            ((TestObject.InnerTestObject) (testObject.myListByInterface.get(1))).string);

    List<List<Integer>> collectionOfCollections = testObject.myCollectionOfCollections;
    assertNotNull("testObject.collectionOfCollections", collectionOfCollections);
    assertEquals("testObject.collectionOfCollections.size()", 2, collectionOfCollections.size());
    assertEquals("testObject.collectionOfCollection[0]", CollectionUtils.newArrayList(1, 2),
            collectionOfCollections.get(0));
    assertEquals("testObject.collectionOfCollection[1]", CollectionUtils.newArrayList(3, 4),
            collectionOfCollections.get(1));

    List<Set<SimpleTestObject>> collectionOfCollectionUtilsOfTestObjects = testObject.mySetsOfTestObjects;
    assertNotNull("testObject.myCollectionUtilsOfTestObjects", collectionOfCollectionUtilsOfTestObjects);
    assertEquals("testObject.myCollectionUtilsOfTestObjects[0][0]",
            CollectionUtils.newHashSet(new SimpleTestObject("post-parse:set 0 child 0", "simpleTestObject"),
                    new SimpleTestObject("post-parse:set 0 child 1", "simpleTestObject")),
            collectionOfCollectionUtilsOfTestObjects.get(0));
    assertEquals("testObject.myCollectionUtilsOfTestObjects[0][0]",
            CollectionUtils.newHashSet(new SimpleTestObject("post-parse:set 1 child 0", "simpleTestObject"),
                    new SimpleTestObject("post-parse:set 1 child 1", "simpleTestObject")),
            collectionOfCollectionUtilsOfTestObjects.get(1));

    assertEquals("testObject.myUnannotatedObject", new UnannotatedObject("singular unannotated object"),
            testObject.myUnannotatedObject);

    assertEquals("testObject.myUnannotatedObjectCollection",
            CollectionUtils.newArrayList(new UnannotatedObject("unannotated item 0"),
                    new UnannotatedObject("unannotated item 1")),
            testObject.myUnannotatedObjectCollection);

    // JSON Natives
    assertNotNull("testObject.myJsonObject", testObject.myJsonObject);
    assertEquals("testObject.myJsonObject.getString(\"name\")", "value",
            testObject.myJsonObject.getString("name"));

    assertNotNull("testObject.myJsonArray", testObject.myJsonArray);
    assertEquals("testObject.myJsonArray.length()", 2, testObject.myJsonArray.length());
    assertEquals("testObject.myJsonArray[0].(\"name 0\")", "value 0",
            ((JSONObject) testObject.myJsonArray.get(0)).getString("name 0"));
    assertEquals("testObject.myJsonArray[1].(\"name 1\")", "value 1",
            ((JSONObject) testObject.myJsonArray.get(1)).getString("name 1"));

    assertNotNull("testObject.myJsonObjectCollection", testObject.myJsonObjectCollection);
    assertEquals("testObject.myJsonObjectCollection.size()", 2, testObject.myJsonObjectCollection.size());
    assertEquals("testObject.myJsonObjectCollection[0].(\"list name 0\")", "list value 0",
            testObject.myJsonObjectCollection.get(0).getString("list name 0"));
    assertEquals("testObject.myJsonObjectCollection[1].(\"list name 1\")", "list value 1",
            testObject.myJsonObjectCollection.get(1).getString("list name 1"));

    // Setters
    assertEquals("testObject.stringFromSetter", "string for setter", testObject.stringFromSetter);
    assertEquals("testObject.unannotatedObjectFromSetter",
            new UnannotatedObject("unannotated object for setter"), testObject.unannotatedObjectFromSetter);
    assertEquals("testObject.testObjectCollectionFromSetter",
            CollectionUtils.newArrayList(new ParserAnnotatedObject("object for list setter 0", null),
                    new ParserAnnotatedObject("object for list setter 1", null)),
            testObject.testObjectCollectionFromSetter);

    assertNotNull("testObject.integerCollectionsFromSetter", testObject.integerCollectionsFromSetter);
    assertEquals("testObject.integerCollectionsFromSetter.size()", 2,
            testObject.integerCollectionsFromSetter.size());
    assertEquals("testObject.integerCollectionsFromSetter.get(0)", CollectionUtils.newHashSet(1, 2),
            testObject.integerCollectionsFromSetter.get(0));
    assertEquals("testObject.integerCollectionsFromSetter.get(1)", CollectionUtils.newHashSet(3, 4),
            testObject.integerCollectionsFromSetter.get(1));

    // Empty Objects
    assertEquals("testObject.myEmptyObject", new SimpleTestObject(), testObject.myEmptyObject);
    assertNotNull("testObject.myEmptyCollection", testObject.myEmptyCollection);
    assertTrue("testObject.myEmptyCollection.isEmpty()", testObject.myEmptyCollection.isEmpty());

    // Nulls
    assertEquals("testObject.myNullInt", 1, testObject.myNullInt);
    assertNull("testObject.myNullString", testObject.myNullString);
    assertNull("testObject.myNullTestObject", testObject.myNullTestObject);
    assertNull("testObject.myNullCollection", testObject.myNullCollection);
    assertEquals("testObject.myDefaultCollection", Collections.singleton("the one"),
            testObject.myDefaultCollection);
}

From source file:org.apache.phoenix.util.PhoenixRuntimeTest.java

@Test
public void testParseArguments_FullOption() {
    PhoenixRuntime.ExecutionCommand execCmd = PhoenixRuntime.ExecutionCommand
            .parseArgs(new String[] { "-t", "mytable", "myzkhost:2181", "--strict", "file1.sql", "test.csv",
                    "file2.sql", "--header", "one, two,three", "-a", "!", "-d", ":", "-q", "3", "-e", "4" });

    assertEquals("myzkhost:2181", execCmd.getConnectionString());

    assertEquals(ImmutableList.of("file1.sql", "test.csv", "file2.sql"), execCmd.getInputFiles());

    assertEquals(':', execCmd.getFieldDelimiter());
    assertEquals('3', execCmd.getQuoteCharacter());
    assertEquals(Character.valueOf('4'), execCmd.getEscapeCharacter());

    assertEquals("mytable", execCmd.getTableName());

    assertEquals(ImmutableList.of("one", "two", "three"), execCmd.getColumns());
    assertTrue(execCmd.isStrict());/*from  w  ww. java 2  s.c  o  m*/
    assertEquals("!", execCmd.getArrayElementSeparator());
}

From source file:de.hybris.platform.commercesearch.searchandizing.boost.impl.DefaultBoostServiceIntegrationTest.java

@Before
public void setUp() throws Exception {
    importService.importData(new StreamBasedImpExResource(
            SolrfacetsearchDataSetup.class.getResourceAsStream("/test/impex/catalog.impex"),
            CSVConstants.HYBRIS_ENCODING, Character.valueOf(';')));
    importService.importData(new StreamBasedImpExResource(
            SolrfacetsearchDataSetup.class.getResourceAsStream("/test/impex/solr.impex"),
            CSVConstants.HYBRIS_ENCODING, Character.valueOf(';')));

    catalogVersion = catalogVersionService.getCatalogVersion(CATALOG, CATALOG_VERSION);
    facetSearchConfig = facetSearchConfigService.getConfiguration(catalogVersion);
    indexedType = getIndexedType(facetSearchConfig);
    solrIndexedType = getSolrIndexedType();
    createCategories();/*from www . j a v  a2 s  .  c o  m*/
}

From source file:jp.furplag.util.commons.ObjectUtils.java

/**
 * substitute for {@link java.lang.Class#newInstance()}.
 *
 * @param type the Class object, return false if null.
 * @return empty instance of specified {@link java.lang.Class}.
 * @throws IllegalArgumentException/*from   w  w w  .j  a v a2s. c  o  m*/
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws ClassNotFoundException
 * @throws NegativeArraySizeException
 */
@SuppressWarnings("unchecked")
public static <T> T newInstance(final Class<T> type) throws InstantiationException {
    if (type == null)
        return null;
    if (type.isArray())
        return (T) Array.newInstance(type.getComponentType(), 0);
    if (Void.class.equals(ClassUtils.primitiveToWrapper(type))) {
        try {
            Constructor<Void> c = Void.class.getDeclaredConstructor();
            c.setAccessible(true);

            return (T) c.newInstance();
        } catch (SecurityException e) {
        } catch (NoSuchMethodException e) {
        } catch (InvocationTargetException e) {
        } catch (IllegalAccessException e) {
        }

        return null;
    }

    if (type.isInterface()) {
        if (!Collection.class.isAssignableFrom(type))
            throw new InstantiationException(
                    "could not create instance, the type \"" + type.getName() + "\" is an interface.");
        if (List.class.isAssignableFrom(type))
            return (T) Lists.newArrayList();
        if (Map.class.isAssignableFrom(type))
            return (T) Maps.newHashMap();
        if (Set.class.isAssignableFrom(type))
            return (T) Sets.newHashSet();
    }

    if (type.isPrimitive()) {
        if (boolean.class.equals(type))
            return (T) Boolean.FALSE;
        if (char.class.equals(type))
            return (T) Character.valueOf(Character.MIN_VALUE);

        return (T) NumberUtils.valueOf("0", (Class<? extends Number>) type);
    }
    if (ClassUtils.isPrimitiveOrWrapper(type))
        return null;
    if (Modifier.isAbstract(type.getModifiers()))
        throw new InstantiationException(
                "could not create instance, the type \"" + type.getName() + "\" is an abstract class.");

    try {
        Constructor<?> c = type.getDeclaredConstructor();
        c.setAccessible(true);

        return (T) c.newInstance();
    } catch (SecurityException e) {
    } catch (NoSuchMethodException e) {
    } catch (InvocationTargetException e) {
    } catch (IllegalAccessException e) {
    }

    throw new InstantiationException("could not create instance, the default constructor of \"" + type.getName()
            + "()\" is not accessible ( or undefined ).");
}

From source file:org.datacleaner.util.convert.StandardTypeConverter.java

@Override
public Object fromString(Class<?> type, String str) {
    if (ReflectionUtils.isString(type)) {
        return str;
    }/*from  www.j  a va  2 s .  c  om*/
    if (ReflectionUtils.isBoolean(type)) {
        return Boolean.valueOf(str);
    }
    if (ReflectionUtils.isCharacter(type)) {
        return Character.valueOf(str.charAt(0));
    }
    if (ReflectionUtils.isInteger(type)) {
        return Integer.valueOf(str);
    }
    if (ReflectionUtils.isLong(type)) {
        return Long.valueOf(str);
    }
    if (ReflectionUtils.isByte(type)) {
        return Byte.valueOf(str);
    }
    if (ReflectionUtils.isShort(type)) {
        return Short.valueOf(str);
    }
    if (ReflectionUtils.isDouble(type)) {
        return Double.valueOf(str);
    }
    if (ReflectionUtils.isFloat(type)) {
        return Float.valueOf(str);
    }
    if (ReflectionUtils.is(type, Class.class)) {
        try {
            return Class.forName(str);
        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException("Class not found: " + str, e);
        }
    }
    if (ReflectionUtils.is(type, EnumerationValue.class)) {
        return new EnumerationValue(str);
    }
    if (type.isEnum()) {
        try {
            Object[] enumConstants = type.getEnumConstants();

            // first look for enum constant matches
            Method nameMethod = Enum.class.getMethod("name");
            for (Object e : enumConstants) {
                String name = (String) nameMethod.invoke(e);
                if (name.equals(str)) {
                    return e;
                }
            }

            // check for aliased enums
            for (Object e : enumConstants) {
                String name = (String) nameMethod.invoke(e);
                Field field = type.getField(name);
                Alias alias = ReflectionUtils.getAnnotation(field, Alias.class);
                if (alias != null) {
                    String[] aliasValues = alias.value();
                    for (String aliasValue : aliasValues) {
                        if (aliasValue.equals(str)) {
                            return e;
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new IllegalStateException("Unexpected error occurred while examining enum", e);
        }
        throw new IllegalArgumentException("No such enum '" + str + "' in enum class: " + type.getName());
    }
    if (ReflectionUtils.isDate(type)) {
        return toDate(str);
    }
    if (ReflectionUtils.is(type, File.class)) {
        final FileResolver fileResolver = new FileResolver(_configuration);
        return fileResolver.toFile(str);
    }
    if (ReflectionUtils.is(type, Calendar.class)) {
        Date date = toDate(str);
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        return c;
    }
    if (ReflectionUtils.is(type, Pattern.class)) {
        try {
            return Pattern.compile(str);
        } catch (PatternSyntaxException e) {
            throw new IllegalArgumentException("Invalid regular expression syntax in '" + str + "'.", e);
        }
    }
    if (ReflectionUtils.is(type, java.sql.Date.class)) {
        Date date = toDate(str);
        return new java.sql.Date(date.getTime());
    }
    if (ReflectionUtils.isNumber(type)) {
        return ConvertToNumberTransformer.transformValue(str);
    }
    if (ReflectionUtils.is(type, Serializable.class)) {
        logger.warn("fromString(...): No built-in handling of type: {}, using deserialization", type.getName());
        byte[] bytes = (byte[]) _parentConverter.fromString(byte[].class, str);
        ChangeAwareObjectInputStream objectInputStream = null;
        try {
            objectInputStream = new ChangeAwareObjectInputStream(new ByteArrayInputStream(bytes));
            objectInputStream.addClassLoader(type.getClassLoader());
            Object obj = objectInputStream.readObject();
            return obj;
        } catch (Exception e) {
            throw new IllegalStateException("Could not deserialize to " + type + ".", e);
        } finally {
            FileHelper.safeClose(objectInputStream);
        }
    }

    throw new IllegalArgumentException("Could not convert to type: " + type.getName());
}