1 | function v = fromJava(jv)
|
---|
2 | %fromJava Convert from Java to Matlab.
|
---|
3 | % fromJava(jv) converts a Java object back into a matlab object, reversing
|
---|
4 | % the action of toJava.
|
---|
5 | %
|
---|
6 | % See also toJava.
|
---|
7 |
|
---|
8 | % Written by Thomas Minka
|
---|
9 | % (c) Microsoft Corporation. All rights reserved.
|
---|
10 |
|
---|
11 | if ~isjava(jv)
|
---|
12 | v = jv;
|
---|
13 | return
|
---|
14 | end
|
---|
15 | % class(jv) is expensive, so we do it only once
|
---|
16 | cl = class(jv);
|
---|
17 | % common cases first
|
---|
18 | if strncmp(cl,'java.lang.Double',16)
|
---|
19 | v = double(jv);
|
---|
20 | return
|
---|
21 | end
|
---|
22 | if strncmp(cl,'java.lang.String',16)
|
---|
23 | v = char(jv);
|
---|
24 | return
|
---|
25 | end
|
---|
26 | if strncmp(cl,'java.lang.Object[]',18)
|
---|
27 | sz = sizeJava(jv);
|
---|
28 | v = cell(1,prod(sz));
|
---|
29 | for i = 1:length(v)
|
---|
30 | index = substruct('()',num2cell(ind2subv(sz,i)));
|
---|
31 | elt = subsref(jv,index);
|
---|
32 | v{i} = fromJava(elt);
|
---|
33 | % this also works:
|
---|
34 | %v = subsasgn(v,index,elt);
|
---|
35 | end
|
---|
36 | v = reshape(v,sz);
|
---|
37 | return
|
---|
38 | end
|
---|
39 | if strcmp(cl,'java.util.Hashtable')
|
---|
40 | v = struct;
|
---|
41 | fields = jv.get('_fields');
|
---|
42 | if ~isempty(fields)
|
---|
43 | % create the fields in the right order
|
---|
44 | ke = fields.elements;
|
---|
45 | else
|
---|
46 | % create the fields in random order
|
---|
47 | ke = jv.keys;
|
---|
48 | end
|
---|
49 | while ke.hasMoreElements
|
---|
50 | f = ke.nextElement;
|
---|
51 | v = setfield(v,char(f),fromJava(jv.get(f)));
|
---|
52 | end
|
---|
53 | c = jv.get('_class');
|
---|
54 | if ~isempty(c)
|
---|
55 | % call the class constructor with the structure as argument
|
---|
56 | % (doesn't work for all classes)
|
---|
57 | v = feval(c,v);
|
---|
58 | end
|
---|
59 | return
|
---|
60 | end
|
---|
61 | if strcmp(cl,'java.util.Vector')
|
---|
62 | v = [];
|
---|
63 | return
|
---|
64 | end
|
---|
65 | if strcmp(cl,'java.util.BitSet')
|
---|
66 | v = {};
|
---|
67 | return
|
---|
68 | end
|
---|
69 | % use matlab's builtin converter from java.lang.Object
|
---|
70 | vec = java.util.Vector;
|
---|
71 | vec.addElement(jv);
|
---|
72 | v = vec.elementAt(0);
|
---|