javax.management.InstanceNotFoundException

javax.management.InstanceNotFoundException

我对 java 中的托管 Bean 比较陌生,我想弄清楚为什么我得到 exception.After 运行 Main.java,我得到了异常粘贴在 bottom.I 试图在 jconsole 上查看它,但它似乎不是 appearing.What 我错过了吗?

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

您还没有 registered 您的 MBean。这样做可能不是最佳做法,但您可以将注册添加到 Worker 构造函数中,以便让事情顺利进行。在创建 ObjectName 后将此行添加到您的构造函数:

this.mbs.registerMBean(this, name);

(您需要为少数新异常添加捕获)

_------

对不起。没有仔细阅读。您需要注册一个 Hello 实例。