wangpeng138375 / pojo-mbean

Automatically exported from code.google.com/p/pojo-mbean
0 stars 0 forks source link

add capability to generate names for objects with multiple instance #28

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
my solution is to add an optional attribute to @MBean which names an operation 
returning an string which would be added to beans name.

here are 3 changes needed to do so:

1) add new attribute

public @interface MBean {
...
   String instanceName() default "";
...
}

2) add code to use it in creating name as ObjectNameBuilder constructor

   public ObjectNameBuilder(Object mbean) throws MalformedObjectNameException {
        Class<?> mBeanClass = mbean.getClass();
        MBean annotation = mBeanClass.getAnnotation(MBean.class);
        if (annotation == null) {
            throw new IllegalArgumentException(mBeanClass + " is not annotated with " + MBean.class);
        }
        String name = annotation.objectName();
        if (!"".equals(annotation.instanceName())) {
            try {
                Method m = mBeanClass.getMethod(annotation.instanceName());
                m.setAccessible(true);
                Object instanceName = m.invoke(mbean);
                // ,instance=xxx
                name = name + instanceName;
            } 
            catch (Exception x) {
                throw new IllegalArgumentException("error calling instance name operation in bean " + MBean.class);
            }
        }
        this.objectName = ObjectName.getInstance(name);
    }

3) change MBeanRegistration constructor to use it

    public MBeanRegistration(Object mBean) throws MalformedObjectNameException {
        this(mBean, new ObjectNameBuilder(mBean).build());
    }

Original issue reported on code.google.com by arash.ra...@gmail.com on 25 Oct 2012 at 10:19