Better code with Jacob and WMI

I am using JACOB to access system information via WMI. I didn't find a lot of documentation for WMI and Jacob on the Internet and I was wondering if I could help make the code more efficient a little.

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 you can see, it looks like there is no point in iterating over the collection for just one item. I would like to just query a single column in a query and get the result from that as quickly and efficiently as possible, with minimal overhead.

Does anyone have a lot of experience with JACOB and getting these values ​​in the best way possible?

Thank,

Steve

+2


source to share


1 answer


I understand that WMI will always return a collection of zero or more items for any ExecQuery. And if the JACOB EnumVariant class is the best way to get information from WMI (from the examples I've seen), you need to enumerate it one way or another.

(You might be able to compress a few more lines, for example 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 else.)



If you are sure that the query will return at most one element - 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 will be much shorter than yours already.

+2


source







All Articles