How to Use Java Proxy Methods which Return java.lang.Object |
|
You may find that after using the com2java tool to generate Java proxy files for your COM component, some of the methods return java.lang.Object. This happens because the COM component's type library does not specify what kind of object is returned by the method call (it just says that it returns IDispatch, IUnknown, or Variant). In other words, the com2java tool does not know what generated Java class/interface to make the method call return, so it makes it return a java.lang.Object.
In order to use the returned Object you need to wrap it with the appropriate proxy/class generated by com2java. The following example will show you how to do this.
Example Type Library Entries
coclass World {
[default] interface _World;>}
interface _World {
HRESULT GetCountry( [out, retval] ICountry** country );
}
interface ICountry {
HRESULT GetCapital( [out, retval] IDispatch** capital );
HRESULT GetLeader( [out, retval] VARIANT** leader );
}
interface ICapital {..}
coclass Leader {..}
Example Code
// create a World
objectWorld world = new World();
// getCountry returns an ICountry interface, so no wrapping necessary
ICountry country = world.getCountry();
// getCapital returns an IDispatch, so wrap it with the ICapitalProxy class
ICapital capital = (ICapital) new ICapitalProxy( country.getCapital() );
// getLeader returns a VARIANT, so wrap it with the Leader class
Leader leader = new Leader( country.getLeader() );
Summary
If the returned Object is a specific interface, then the general syntax is...
ISomeInterface obj = (ISomeInterface) new ISomeInterfaceProxy( obj2.getAnObj() );
If the returned Object is a specific class, then the general syntax is...
SomeClass obj = new SomeClass( obj2.getAnObj() );