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.
source share