get Java Bean Simple Property Write Method - Java Reflection

Java examples for Reflection:Java Bean

Description

get Java Bean Simple Property Write Method

Demo Code


//package com.java2s;
import java.beans.BeanInfo;

import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Main {
    public static Method getSimplePropertyWriteMethod(Object bean,
            String name) throws IllegalArgumentException,
            IllegalAccessException, InvocationTargetException {
        PropertyDescriptor propertyDescriptor = getPropertyDescriptor(bean,
                name);//from w  ww  . jav  a2 s  . com
        if (propertyDescriptor == null)
            throw new IllegalArgumentException("No property:" + name);
        return propertyDescriptor.getWriteMethod();
    }

    public static PropertyDescriptor getPropertyDescriptor(Object bean,
            String name) {
        PropertyDescriptor[] descriptors = getPropertyDescriptors(bean);
        for (int i = 0; i < descriptors.length; i++) {
            if (name.equals(descriptors[i].getName()))
                return descriptors[i];
        }
        return null;
    }

    public static PropertyDescriptor[] getPropertyDescriptors(Object bean) {
        BeanInfo beanInfo = null;
        try {
            beanInfo = Introspector.getBeanInfo(bean.getClass());
        } catch (IntrospectionException e) {
            return (new PropertyDescriptor[0]);
        }
        PropertyDescriptor[] descriptors = beanInfo
                .getPropertyDescriptors();
        return descriptors;
    }
}

Related Tutorials