I am using JACOB to access system information through WMI. I have not found much documentation for WMI and Jacob on the web and was wondering if I could get some help in making the code a little more efficient.
Here is the code:
ActiveXComponent mActiveXWMI = new ActiveXComponent("winmgmts:\\\\localhost\\root\\CIMV2");
String query = "SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor WHERE Name='_Total'";
Variant vCollection = mActiveXWMI.invoke("ExecQuery", new Variant(query));
EnumVariant enumVariant = new EnumVariant(vCollection.toDispatch());
Dispatch item = null;
while (enumVariant.hasMoreElements()) {
item = enumVariant.nextElement().toDispatch();
cpuUsage = Double.parseDouble(Dispatch.call(item, "PercentProcessorTime").toString());
}
As one can see, it doesn't seem to make much sense of looping through a collection for just one item. I would like to just query for one column in the query statement and get the result from that as quickly and efficiently as possible, with as little overhead as possible.
Does anyone have much experience with JACOB and retrieving these values in the best way possible?
Thanks,
Steve
My understanding is that in general, WMI will always return a collection of zero or more items for any ExecQuery. And if JACOB's EnumVariant class is the best way to receive the info from WMI (from the examples I've seen), then you need to enumerate through it in one way or another.
(You might be able to compress a few more lines together, like
EnumVariant enumVariant = new EnumVariant( mActiveXWMI.invoke("ExecQuery", new Variant(query)).toDispatch() );
--but that makes it even harder to read, and won't help performance or anything.)If you're certain the query will return no more than one item--as in your example--you could change the "while" to an "if" statement (and then handle the case where it fails in your "else" clause).
But otherwise... I don't think it's going to get much shorter than what you have already.