我对java中的Managed Beans相对较新,我试图弄清楚为什么我得到一个异常。运行Main.java后,我得到了粘贴在底部的异常。我试图在jconsole上查看它但是它似乎没有出现。我错过了什么?
Hello.java
package com.mbeans;
public class Hello implements HelloMBean {
private final String name = "Reginald";
private int cacheSize = DEFAULT_CACHE_SIZE;
private static final int
DEFAULT_CACHE_SIZE = 200;
public void sayHello() {
System.out.println("hello, world");
}
public int add(int x, int y) {
return x + y;
}
public String getName() {
return this.name;
}
public int getCacheSize() {
return this.cacheSize;
}
public synchronized void setCacheSize(int size) {
this.cacheSize = size;
System.out.println("Cache size now " + this.cacheSize);
}
}
HelloMBean.java
package com.mbeans;
public interface HelloMBean {
public void sayHello();
public int add(int x, int y);
public String getName();
public int getCacheSize();
public void setCacheSize(int size);
}
Main.java
package com.mbeans;
import java.lang.management.*;
import javax.management.*;
public class Main {
public static void main(String[] args)
throws Exception {
Worker worker = new Worker();
}
}
Worker.java
package com.mbeans;
import java.lang.management.ManagementFactory;
import java.util.logging.Level;
import javax.management.MBeanServer;
import javax.management.MBeanServerInvocationHandler;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
public class Worker {
MBeanServer mbs;
HelloMBean mbean;
public Worker()
{
this.mbs = ManagementFactory.getPlatformMBeanServer();
ObjectName name = null;
try
{
name = new ObjectName("com.mbeans:type=HelloMBean");
}
catch (MalformedObjectNameException ex)
{
ex.printStackTrace();
}
try
{
this.mbean = ((HelloMBean)MBeanServerInvocationHandler.newProxyInstance(this.mbs, name, HelloMBean.class, false));
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println("online : " +this.mbean.add(3, 4));
}
}
这是我得到的例外
Exception in thread "main" java.lang.reflect.UndeclaredThrowableException
at com.sun.proxy.$Proxy2.add(Unknown Source)
at com.mbeans.Worker.<init>(Worker.java:45)
at com.mbeans.Main.main(Main.java:12)
Caused by: javax.management.InstanceNotFoundException: com.mbeans:type=HelloMBean
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.getMBean(Unknown Source)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(Unknown Source)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(Unknown Source)
at javax.management.MBeanServerInvocationHandler.invoke(Unknown Source)
... 3 more
答案 0 :(得分:1)
你没有registered你的MBean。这样做可能不是最佳做法,但您可以将注册添加到 Worker 构造函数中,以便完成任务。在创建ObjectName后,将此行添加到构造函数中:
this.mbs.registerMBean(this, name);
(您需要为少数新例外添加捕获量)
_------
对不起。没仔细阅读。您需要注册Hello的实例。