Find the specified property for the given class. - Java java.util

Java examples for java.util:Properties File

Description

Find the specified property for the given class.

Demo Code


//package com.java2s;

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

public class Main {
    public static void main(String[] argv) throws Exception {
        Class clazz = String.class;
        String property = "java2s.com";
        System.out.println(findProperty(clazz, property));
    }// ww  w.ja  va 2  s  . c om

    /**
     * Find the specified property for the given class.
     *
     * @param clazz The class.
     * @param property The property.
     * @return The property descriptor.
     */
    public static PropertyDescriptor findProperty(Class clazz,
            final String property) {
        if (Object.class.equals(clazz)) {
            return null;
        }

        BeanInfo beanInfo;
        try {
            beanInfo = Introspector.getBeanInfo(clazz);
        } catch (IntrospectionException e) {
            throw new IllegalStateException(e);
        }

        PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor pd : pds) {
            if (pd.getName().equals(property)) {
                return pd;
            }
        }

        return findProperty(clazz.getSuperclass(), property);
    }
}

Related Tutorials