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

I want to create a method that can convert a String value to a given data type of a Field object 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 on the first try, I get this java.lang.ClassCastException exception.

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

What is my code missing?

+4
source share
8 answers

Here is the solution I came up with:

 public static Object parse(String value, Class<?> clazz) throws NotSupportedException { String canonClassName = clazz.getCanonicalName(); if (canonClassName.equalsIgnoreCase("java.math.BigDecimal")) { return new BigDecimal(value); } // Add other supported classes here ... throw new NotSupportedException("The class [" + canonClassName + "] is not supported."); } 
0
source

You can do this job for classes with a string constructor as follows: f.getType().getConstructor( String.class ).newInstance( value );

+8
source

In Java, there is no universal method for converting String to an instance of an arbitrary class. Many classes simply do not support such a conversion. And there is no standard interface for those who support it.

It is best to look for a constructor that takes String as its only argument. Of course, not every class provides such a constructor, and there is no guarantee that the semantics will be what you expect.

+3
source

There is a Github project (MIT Licensed) called type-parser that converts a string value to the desired data type

Here is a description of the project from GitHub

This is a small library that does nothing but parse a string of a specific type. Supports all applicable Java classes such as Integer, File, Enum, Float, etc., Including general collection types / interfaces such as List, Set, Map, arrays, and even custom types. It is also possible to register your own parsers.

+2
source

As maerics said, you cannot just pass a String to a data type. Is it possible that you mean "how to parse BigDecimal from String", which answers ...

 fieldName = new BigDecimal(value); 
+1
source

The cast method of the class throws a ClassCastException if the object is not null and cannot be assigned to type T. There are only a few types of variables that can be assigned the reference String, String, Object, Serializable, Comparable, and CharSequence.

Many, but not all, classes have ways to instantiate an object based on String. In some cases, including BigDecimal, there is a constructor that takes a string representation of the new value of the object. You can use the getDeclaredConstructor class method that defines one String argument to get the Constructor object for such a constructor, if any. However, there is a certain risk that you will not get a useful object, for example, by calling some setXXX methods, and this approach is limited to those classes that have the correct constructor form.

Presumably you are trying to solve a higher level problem, possibly related to serialization and deserialization. This problem can be much more easily resolved than your current problem.

+1
source

Perhaps without answering the question of how to convert a String to a java type, since there is no general way to do this. But there is a library that can help you with this. See type-parser . Here, as the sniped code above might look like this:

  String value = ...; Class<? extends MyObject> clazz = getClazz(); Field f = clazz.getDeclaredField("fieldName"); boolean fieldIsAccessible = f.isAccessible(); if (!fieldIsAccessible) { f.setAccessible(true); } TypeParser parser = TypeParser.newBuilder().build(); // parse value to whatever type f.getGenericType() returns Object o = parser.parseType(value, f.getGenericType()); if (!fieldIsAccessible) { f.setAccessible(false); } } 
+1
source

I found my answer in this thread: How to convert a String object to a Boolean Object? - you can parse strings with boolers using:

 Boolean boolean1 = Boolean.valueOf("true"); boolean boolean2 = Boolean.parseBoolean("true"); 
+1
source

All Articles