The open source VI Java API has implemented typing which makes it much easier to use and possible to catch errors in compile time. To use these types, you have to get hold of these objects. Normally you don’t need to worry about this because you navigate the system from the top ServiceInstance and get the managed objects through VI Java API calls.
There are some rare cases in which you get the object id first, for example, a task id as asked in the VI Java API forum. A bit more common case is when you develop vSphere Client plug-ins. The URL string your web application gets has object id and type for a virtual machine or host, etc.
Bothered by SLOW Web UI to manage vSphere? Want to manage ALL your VMware vCenters, AWS, Azure, Openstack, container behind a SINGLE pane of glass? Want to search, analyze, report, visualize VMs, hosts, networks, datastores, events as easily as Google the Web? Find out more about vSearch 3.0: the search engine for all your private and public clouds.
Although coming from different use cases, it’s the same for API usage. You have two choices:
1. If you know both the type and id of the managed object, you can simply follow the following code. Make sure you type the name of the managed object correctly. Note that you can also replace the last line of code in first approach with the code of second approach.
ManagedObjectReference mor = new ManagedObjectReference(); mor.setType("Task"); mor.setVal("task-123"); Task task = new Task(si.getServerConnection(), mor);
2. If you have ManagedObjectReference object instead (more common if you use API to drill down some properties to their sub-properties), you can simply use a utility as the following. Note that you have to cast the type by yourself, meaning as a programmer you have to know the exact type before hand. To play safer, you can test the type before you cast.
Task task1 = (Task) MorUtil.createExactManagedObject(si.getServerConnection(), mor); // or if you know the object will be a ManagedEntity VirtualMachine vm = (VirtualMachine) MorUtil.createExactManagedObject(si.getServerConnection(), mor);
Note that the si variable in both code snippets is a reference to a ServiceInstance object. Because getServerConnection() is defined in ManagedObject type, so you can use any reference to a VirtualMachine, HostSystem, etc.