Method for determining the get method belonging to a particular attribute. - Java Reflection

Java examples for Reflection:Method

Description

Method for determining the get method belonging to a particular attribute.

Demo Code

//   Licensed under the Apache License, Version 2.0 (the "License");
//package com.java2s;
import java.lang.reflect.Method;
import javax.management.Descriptor;
import javax.management.MBeanException;

import javax.management.modelmbean.ModelMBeanAttributeInfo;
import javax.management.modelmbean.ModelMBeanInfo;

public class Main {
    /**//from   w  ww . j av  a 2 s .c om
     * Method for determining the get method belonging to a particular
     * attribute.
     *
     * @param aModelMBeanInfo
     * @param aManagedBean
     * @param aAttribute
     * @return Method
     * @throws MBeanException
     */
    public static Method findGetMethod(ModelMBeanInfo aModelMBeanInfo,
            Object aManagedBean, String aAttribute) throws MBeanException {
        try {
            ModelMBeanAttributeInfo lInfo = aModelMBeanInfo
                    .getAttribute(aAttribute);
            Descriptor lDescriptor = lInfo.getDescriptor();
            String lMethodName = (String) (lDescriptor
                    .getFieldValue("getMethod"));
            if (lMethodName == null) {
                lMethodName = toMethodName("get", aAttribute);
            }
            return aManagedBean.getClass().getMethod(lMethodName,
                    new Class[] {});
        } catch (NoSuchMethodException e) {
            throw new MBeanException(e);
        }
    }

    /**
     * Method used to construct the name of a method given a prefix.
     *
     * @param aPrefix
     * @param aName
     * @return
     */
    protected static String toMethodName(String aPrefix, String aName) {
        char lHead = Character.toUpperCase(aName.charAt(0));
        String lTail = aName.substring(1);
        return aPrefix + lHead + lTail;
    }
}

Related Tutorials