我想使用MBeanServer.queryMBeans(ObjectName name,QueryExp查询)来获取带有查询表达式的MBean,但它似乎并不真正适用于QueryExp查询。例如,我有这样的测试代码:
public class CreateAndRegisterMBeanInMBeanServer {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
String objectName = "com.javacodegeeks.snippets.enterprise:type=Hello";
QueryExp exp = Query.eq(Query.attr("type"), Query.value("Hello"));
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
// Construct the ObjectName for the Hello MBean we will register
ObjectName mbeanName = new ObjectName(objectName);
Hello mbean = new Hello();
server.registerMBean(mbean, mbeanName);
Set<ObjectInstance> instances = server.queryMBeans(new ObjectName(objectName), null);
System.out.println(instances.size());
for (int i = 0; i < instances.size(); i++) {
ObjectInstance instance = (ObjectInstance) instances.toArray()[i];
System.out.println("Class Name:t" + instance.getClassName());
System.out.println("Object Name:t" + instance.getObjectName());
}
}
static class Hello implements HelloMBean {
private String message = "Hello World";
@Override
public String getMessage() {
return this.message;
}
@Override
public void sayHello() {
System.out.println(message);
}
@Override
public void setMessage(String message) {
this.message = message;
}
}
static interface HelloMBean {
// operations
public void sayHello();
// attributes
// a read-write attribute called Message of type String
public String getMessage();
public void setMessage(String message);
}
}
我可以预料到: 1 类名:tCreateAndRegisterMBeanInMBeanServer $ Hello 对象名称:tcom.javacodegeeks.snippets.enterprise:type = Hello
但是,如果我将我的代码更改为使用已定义的QueryExp exp为:
Set instances = server.queryMBeans(new ObjectName(objectName),exp);
我看不到任何选定的MBean,这是使用这种Query Exp的正确方法吗?
谢谢,
答案 0 :(得分:5)
更改
QueryExp exp = Query.eq(Query.attr("type"), Query.value("Hello"));
到
QueryExp exp = Query.eq(Query.attr("Message"), Query.value("Hello World"));
因为类型“type”不是属性。
或者,如果您尝试通过“类型”查询,这是ObjectName
的一部分,您可以像这样构造对象名称:
String objectName = "*:type=Hello";
然后像以前一样进行查询:
Set<ObjectInstance> instances = server.queryMBeans(new ObjectName(objectName), null);
请参阅http://codeidol.com/java/java-jmx/The-MBeanServer/Finding-MBeans/