javastringclasscastexceptionjni4net

java.lang.String cannot be cast to system.Object


I have used JNI4NET framework to invoke .Net code from Java. JNI4NET has generated proxy class for .Net code. One of the methods accept system.Object as an input parameter.

I want to send String value as input to that method. I have wrote the below code for that-

        String s = "test";
        Object b = s;
        system.Object object = (system.Object) b;

And passing this obj as an input to proxy method. The above code throws runtime exception java.lang.String cannot be cast to system.Object. Any help or pointers will be useful.


Solution

  • java.lang.String can be cast to java.lang.Object (though there's no reason to cast it - you can simply assign it to an Object reference as you do in - Object b = s;), not to system.Object.

    I did some searching. It looks like this might help :

    String s = "test";
    system.String b = new system.String(s);
    system.Object object = b;
    

    Since system.String is a sub-class of system.Object, you can pass it to your test method.