octave-bug-tracker
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Octave-bug-tracker] [bug #42701] java toString method returns char inst


From: Andrew Janke
Subject: [Octave-bug-tracker] [bug #42701] java toString method returns char instead of java.lang.String
Date: Thu, 19 Jul 2018 01:08:11 -0400 (EDT)
User-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36

Follow-up Comment #6, bug #42701 (project octave):

Wait, wait. I take that back. The documentation is correct, but you have to
read and parse it _very_ carefully.

The doco starts off by saying: "When a Java method is declared to return data
of type java.lang.Object, MATLAB converts its value depending on the actual
type returned." This conversion only happens when _exactly_ that situation is
true: you call a method whose declared return type is exactly
java.lang.Object, and not a subclass of Object.

Consider this Java class:


package net.janklab.test;

public class DemoType {

    public Object getData() {
        return new java.lang.Integer(42);
    }

    public Integer getDataAsInteger() {
        return new java.lang.Integer(42);
    }

    public Object getStringAsObject() {
        return "foo";
    }

    public String getStringAsString() {
        return "foo";
    }
}


Those getData() and getDataAsInteger() methods return exactly equivalent Java
objects: Integers containing the value 42. But they are converted
differently.


>> obj = net.janklab.test.DemoType
obj =
address@hidden
>> x = obj.getData
x =
    42
>> class(x)
ans =
    'double'
>> y = obj.getDataAsInteger
y =
42
>> class(y)
ans =
    'java.lang.Integer'
>> 


> ...says that a Java return value of java.lang.String should be
auto-converted into a Matlab type char value...

So, yes, it will be auto-converted, but only if it comes out of a method
declared to return exactly Object, and not one declared to return String, even
though the run-time Java values are equivalent.


>> obj = net.janklab.test.DemoType
obj =
address@hidden
>> s1 = obj.getStringAsObject
s1 =
    'foo'
>> class(s1)
ans =
    'char'
>> s2 = obj.getStringAsString
s2 =
foo
>> class(s2)
ans =
    'java.lang.String'
>> 


And so, since normal toString() methods are declared to return String and not
Object, their return values are not subject to auto-conversion, and remain
java.lang.String objects.

If you ask me, this is wacky behavior, and no wonder we're all confused. I've
been coding Java+Matlab for nearly 15 years now, and never understood this
subtlety until now.

    _______________________________________________________

Reply to this item at:

  <http://savannah.gnu.org/bugs/?42701>

_______________________________________________
  Message sent via Savannah
  https://savannah.gnu.org/




reply via email to

[Prev in Thread] Current Thread [Next in Thread]