java - Casting a String to a Number in generic class -


I have a number that can change the user through a GUI. The GUI has a TextField (JavaFX) where they can write desirable value.

Since I wanted this class to be flexible, I made it using generic:

  public class configurablemumeric field & lt; T number increases & gt; {Private T-value; // ... public null set value (t value) {this.value = value; }}   

And I am creating an object like this:

  configurable numeric field < Integer & gt; Foo = New ConfigurableNumericField & lt; & Gt; (/*...*/);   

The problem is that TextField returns a CharacterSequence (which can be applied to string ). But even though the valueOf method is not , number in all the sections derived from the number .

Then when I try to do the class myself with TextField from setValue () to string I can not put a java.lang.ClassCastException: java.lang.String in java.lang.Number. .

How can I do this?

When generic you can make things so normal that they are no longer worthwhile.

In your case, you need a set val that will take the string so you can convert it to the appropriate type. The problem with this is that there is no way to do this normally because the normal type of foo is not available at runtime.

I will have two subclasses, one long and one that uses double or BigDecimal . This may require most number of types.

Comments