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
  • 80,457
  • 12
  • 86
  • 114
Akansha Gautam
  • 77
  • 1
  • 10

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
  • 947
  • 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

Mustapha Belmokhtar
  • 1,231
  • 8
  • 21