Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a String variable into any data type in Java?

I want to build a method that can convert a String value to a given Field object data type through Java Reflection.

Here is my code:

String value = ...;

Class<? extends MyObject> clazz = getClazz();

Field f = clazz.getDeclaredField("fieldName");
boolean fieldIsAccessible = f.isAccessible();
if (!fieldIsAccessible) {
   f.setAccessible(true);
}

f.getType().cast(value);

if (!fieldIsAccessible) {
    f.setAccessible(false);
}

When I run this code at firs attempt, I receive this exception java.lang.ClassCastException.

I want to convert value to class java.math.BigDecimal.

What is my code missing ?

EDIT: View the solution I came up with.

like image 792
Stephan Avatar asked Nov 26 '12 16:11

Stephan


People also ask

How do you parse a string in Java?

String parsing in java can be done by using a wrapper class. Using the Split method, a String can be converted to an array by passing the delimiter to the split method. The split method is one of the methods of the wrapper class. String parsing can also be done through StringTokenizer.

Is there a parse for string?

A parsing operation converts a string that represents a . NET base type into that base type. For example, a parsing operation is used to convert a string to a floating-point number or to a date-and-time value. The method most commonly used to perform a parsing operation is the Parse method.

Can we convert string to int in Java?

In Java, we can use Integer.valueOf() and Integer.parseInt() to convert a string to an integer.


3 Answers

You could make this work for classes that have a string constructor like this: f.getType().getConstructor( String.class ).newInstance( value );

like image 154
tibtof Avatar answered Nov 09 '22 19:11

tibtof


In Java, there is no universal method for converting a String into an instance of an arbitrary class. Many classes simply don't support such a conversion. And there's no standard interface for those that do support it.

Your best bet is to look for a constructor that accepts a String as its sole argument. Of course, not every class provides such a constructor, and there's no guarantee that the semantics would be what you'd expect.

like image 31
NPE Avatar answered Nov 09 '22 19:11

NPE


There is a Github project (MIT Licensed) called type-parser which does converting a string value to the desired data type

Here is the project description from GitHub

This is a light weight library that does nothing but parse a string to a given type. Supports all applicable java classes, such as Integer, File, Enum, Float etc., including generic Collection types/interfaces such as List, Set, Map, arrays and even custom made types. Also possible to register your own parsers.

like image 36
Dungeon Hunter Avatar answered Nov 09 '22 19:11

Dungeon Hunter