1

I am using javafx.
I have to convert a variable of Object type to StringProperty type.

Object v = "var";
StringProperty var = (StringProperty) v;

I am not getting any compile time error. But java.lang.ClassCastException shows up.
Thanks

fabian
  • 72,938
  • 12
  • 79
  • 109

2 Answers2

5

You cannot cast an Object containing a String value to a StringProperty.

But you can instantiate a StringProperty from an Object containing a String:

  Object v = "var";
  StringProperty var = new SimpleStringProperty((String) v);
DeiAndrei
  • 927
  • 6
  • 16
1

Why assign a String value to an Object? , I suggest

    String v = "var";
    StringProperty = new SimpleStringProperty(v);

or

    Object v = "var"; // assignment may come from elsewhere
    StringProperty var;
    if (v instanceof String) {
        var = new SimpleStringProperty((String) v);
    }

    else {
        //.. doSomethingElse 
    }

this is done just to avoid any kind of exception

мυѕτавєւмo
  • 1,219
  • 7
  • 20