Search in sources :

Example 26 with BeanInfo

use of java.beans.BeanInfo in project JMRI by JMRI.

the class DefaultJavaBeanConfigXML method store.

@Override
public Element store(Object o) {
    Element e = new Element("javabean");
    e.setAttribute("class", this.getClass().getName());
    e.setAttribute("beanClass", o.getClass().getName());
    try {
        // reflect through and add parameters
        BeanInfo b = Introspector.getBeanInfo(o.getClass());
        PropertyDescriptor[] properties = b.getPropertyDescriptors();
        for (int i = 0; i < properties.length; i++) {
            if (properties[i].getName().equals("class")) {
                // we skip this one
                continue;
            }
            if (properties[i].getPropertyType() == null) {
                log.warn("skipping property with null type: " + properties[i].getName());
                continue;
            }
            Element p = new Element("property");
            Element n = new Element("name");
            n.addContent(properties[i].getName());
            n.setAttribute("type", properties[i].getPropertyType().toString());
            p.addContent(n);
            Element v = new Element("value");
            if (properties[i].getReadMethod() != null) {
                Object value = properties[i].getReadMethod().invoke(o, (Object[]) null);
                if (value != null) {
                    v.addContent(value.toString());
                }
            }
            p.addContent(v);
            e.addContent(p);
        }
    } catch (java.beans.IntrospectionException ex) {
        log.error("Partial store due to IntrospectionException: " + ex);
    } catch (java.lang.reflect.InvocationTargetException ex) {
        log.error("Partial store due to InvocationTargetException: " + ex);
    } catch (IllegalAccessException ex) {
        log.error("Partial store due to IllegalAccessException: " + ex);
    }
    return e;
}
Also used : PropertyDescriptor(java.beans.PropertyDescriptor) Element(org.jdom2.Element) BeanInfo(java.beans.BeanInfo)

Example 27 with BeanInfo

use of java.beans.BeanInfo in project jdk8u_jdk by JetBrains.

the class GenSwingBeanInfo method genBeanInfo.

/**
     * Generates the BeanInfo source file using instrospection and a
     * Hashtable full of hints. This the only public method in this class.
     *
     * @param classname Root name of the class. i.e., JButton
     * @param dochash A hashtable containing the DocBeanInfo.
     */
public void genBeanInfo(String packageName, String classname, Hashtable dochash) {
    // The following initial values are just examples.  All of these
    // fields are initialized below.
    String beanClassName = "JInternalFrame";
    String beanClassObject = "javax.swing.JInternalFrame.class";
    String beanDescription = "<A description of this component>.";
    String beanPropertyDescriptors = "<createSwingPropertyDescriptor code>";
    String classPropertyDescriptors = "<createSwingClassPropertyDescriptor code>";
    Class cls = getClass(packageName, classname);
    if (cls == null) {
        messageAndExit("Can't find class: " + classname);
    }
    // Get the output stream.
    PrintStream out = initOutputFile(classname);
    // Run the Introspector and initialize the variables
    BeanInfo beanInfo = null;
    BeanDescriptor beanDescriptor = null;
    try {
        if (cls == javax.swing.JComponent.class) {
            // Go all the way up the heirarchy for JComponent
            beanInfo = Introspector.getBeanInfo(cls);
        } else {
            beanInfo = Introspector.getBeanInfo(cls, cls.getSuperclass());
        }
        beanDescriptor = beanInfo.getBeanDescriptor();
        beanDescription = beanDescriptor.getShortDescription();
    } catch (IntrospectionException e) {
        messageAndExit("Introspection failed for " + cls.getName() + " " + e);
    }
    beanClassName = beanDescriptor.getName();
    beanClassObject = cls.getName() + ".class";
    if (DEBUG) {
        System.out.println(">>>>GenSwingBeanInfo class: " + beanClassName);
    }
    // Generate the Class BeanDescriptor information first
    if (dochash.size() > 0) {
        if (dochash.containsKey(beanClassName)) {
            DocBeanInfo dbi = (DocBeanInfo) dochash.remove(beanClassName);
            classPropertyDescriptors = genBeanDescriptor(dbi);
            if (DEBUG)
                System.out.println("ClassPropertyDescriptors: " + classPropertyDescriptors);
            if (!(dbi.desc.equals("null")))
                beanDescription = dbi.desc;
        } else
            beanDescription = beanDescriptor.getShortDescription();
    } else
        beanDescription = beanDescriptor.getShortDescription();
    // Generate the Property descriptors
    beanPropertyDescriptors = genPropertyDescriptors(beanInfo, dochash);
    // Dump the template to out, substituting values for
    // @(token) tokens as they're encountered.
    int currentIndex = 0;
    // not loading this to get around build issue for now
    String template = loadTemplate();
    // current class.
    while (currentIndex < template.length()) {
        // Find the Token
        int tokenStart = template.indexOf("@(", currentIndex);
        if (tokenStart != -1) {
            out.print(template.substring(currentIndex, tokenStart));
            int tokenEnd = template.indexOf(")", tokenStart);
            if (tokenEnd == -1) {
                messageAndExit("Bad @(<token>) beginning at " + tokenStart);
            }
            String token = template.substring(tokenStart + 2, tokenEnd);
            if (token.equals(TOK_BEANCLASS)) {
                out.print(beanClassName);
            } else if (token.equals(TOK_CLASSDESC)) {
                if (!(classPropertyDescriptors.equals("<createSwingClassPropertyDescriptor code>"))) {
                    printDescriptors(out, classPropertyDescriptors, template, tokenStart);
                }
            } else if (token.equals(TOK_BEANPACKAGE)) {
                out.print(packageName);
            } else if (token.equals(TOK_BEANOBJECT)) {
                out.print(beanClassObject);
            } else if (token.equals(TOK_BEANDESC)) {
                out.print(beanDescription);
            } else if (token.equals(TOK_ENUMVARS)) {
                out.print(enumcode);
            } else if (token.equals(TOK_PROPDESC)) {
                printDescriptors(out, beanPropertyDescriptors, template, tokenStart);
            } else if (token.equals("#")) {
            // Ignore the @(#) Version Control tag if it exists.
            } else {
                messageAndExit("Unrecognized token @(" + token + ")");
            }
            currentIndex = tokenEnd + 1;
        } else {
            // tokenStart == -1 - We are finsihed.
            out.print(template.substring(currentIndex, template.length()));
            break;
        }
    }
    out.close();
}
Also used : BeanDescriptor(java.beans.BeanDescriptor) BeanInfo(java.beans.BeanInfo) IntrospectionException(java.beans.IntrospectionException)

Example 28 with BeanInfo

use of java.beans.BeanInfo in project Gargoyle by callakrsos.

the class PivotTableViewExam method toMap.

/**
	 * 빈을 Map으로 변환한다. 기본형 데이터만 Map으로 변환한다.
	 *
	 * @작성자 : KYJ
	 * @작성일 : 2016. 2. 12.
	 * @param t
	 * @param isNullBinding
	 *            값이 빈경우 map에 바인딩할지 유무를 지정.
	 * @return
	 * @throws Exception
	 */
public static <T> Map<String, Object> toMap(final T t, boolean isNullBinding) {
    Map<String, Object> hashMap = new HashMap<String, Object>();
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(t.getClass());
        // Iterate over all the attributes
        for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) {
            // write메소드와 read메소드가 존재할때만.
            Method writeMethod = descriptor.getWriteMethod();
            Method readMethod = descriptor.getReadMethod();
            if (ValueUtil.isEmpty(writeMethod) || ValueUtil.isEmpty(readMethod)) {
                continue;
            }
            // Class<?> returnType = readMethod.getReturnType();
            String methodName = ValueUtil.getSimpleMethodName(readMethod.getName());
            Object originalValue = readMethod.invoke(t);
            // SET문등 수행시 타입 오류 발생
            if (ValueUtil.isNotEmpty(originalValue)) {
                hashMap.put(methodName, originalValue);
            } else {
                if (isNullBinding)
                    hashMap.put(methodName, null);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return hashMap;
}
Also used : PropertyDescriptor(java.beans.PropertyDescriptor) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) BeanInfo(java.beans.BeanInfo) Method(java.lang.reflect.Method)

Example 29 with BeanInfo

use of java.beans.BeanInfo in project rabbitmq-java-client by rabbitmq.

the class JSONWriter method writeLimited.

/**
 * Write only a certain subset of the object's properties and fields.
 * @param klass the class to look up properties etc in
 * @param object the object
 * @param properties explicit list of property/field names to include - may be null for "all"
 */
public void writeLimited(Class<?> klass, Object object, String[] properties) {
    Set<String> propertiesSet = null;
    if (properties != null) {
        propertiesSet = new HashSet<String>();
        for (String p : properties) {
            propertiesSet.add(p);
        }
    }
    add('{');
    indentLevel += 2;
    newline();
    boolean needComma = false;
    BeanInfo info;
    try {
        info = Introspector.getBeanInfo(klass);
    } catch (IntrospectionException ie) {
        info = null;
    }
    if (info != null) {
        PropertyDescriptor[] props = info.getPropertyDescriptors();
        for (int i = 0; i < props.length; ++i) {
            PropertyDescriptor prop = props[i];
            String name = prop.getName();
            if (propertiesSet == null && name.equals("class")) {
                // We usually don't want the class in there.
                continue;
            }
            if (propertiesSet == null || propertiesSet.contains(name)) {
                Method accessor = prop.getReadMethod();
                if (accessor != null && !Modifier.isStatic(accessor.getModifiers())) {
                    try {
                        Object value = accessor.invoke(object, (Object[]) null);
                        if (needComma) {
                            add(',');
                            newline();
                        }
                        needComma = true;
                        add(name, value);
                    } catch (Exception e) {
                    // Ignore it.
                    }
                }
            }
        }
    }
    Field[] ff = object.getClass().getDeclaredFields();
    for (int i = 0; i < ff.length; ++i) {
        Field field = ff[i];
        int fieldMod = field.getModifiers();
        String name = field.getName();
        if (propertiesSet == null || propertiesSet.contains(name)) {
            if (!Modifier.isStatic(fieldMod)) {
                try {
                    Object v = field.get(object);
                    if (needComma) {
                        add(',');
                        newline();
                    }
                    needComma = true;
                    add(name, v);
                } catch (Exception e) {
                // Ignore it.
                }
            }
        }
    }
    indentLevel -= 2;
    newline();
    add('}');
}
Also used : PropertyDescriptor(java.beans.PropertyDescriptor) BeanInfo(java.beans.BeanInfo) IntrospectionException(java.beans.IntrospectionException) Method(java.lang.reflect.Method) IntrospectionException(java.beans.IntrospectionException) Field(java.lang.reflect.Field)

Example 30 with BeanInfo

use of java.beans.BeanInfo in project flowml by beautifulNow1992.

the class BeanToMapUtil method convertBean.

/**
 * 将一个 JavaBean 对象转化为一个  Map
 *
 * @param bean 要转化的JavaBean 对象
 * @return 转化出来的  Map 对象
 * @throws IntrospectionException    如果分析类属性失败
 * @throws IllegalAccessException    如果实例化 JavaBean 失败
 * @throws InvocationTargetException 如果调用属性的 setter 方法失败
 */
public static Map<String, Object> convertBean(Object bean) throws IntrospectionException, IllegalAccessException, InvocationTargetException {
    Class type = bean.getClass();
    Map<String, Object> returnMap = new HashMap<String, Object>();
    BeanInfo beanInfo = Introspector.getBeanInfo(type);
    PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    for (int i = 0; i < propertyDescriptors.length; i++) {
        PropertyDescriptor descriptor = propertyDescriptors[i];
        String propertyName = descriptor.getName();
        if (!propertyName.equals("class")) {
            Method readMethod = descriptor.getReadMethod();
            Object result = readMethod.invoke(bean);
            if (result != null) {
                returnMap.put(propertyName, result);
            } else {
                returnMap.put(propertyName, "");
            }
        }
    }
    return returnMap;
}
Also used : PropertyDescriptor(java.beans.PropertyDescriptor) HashMap(java.util.HashMap) BeanInfo(java.beans.BeanInfo) Method(java.lang.reflect.Method)

Aggregations

BeanInfo (java.beans.BeanInfo)420 PropertyDescriptor (java.beans.PropertyDescriptor)328 Method (java.lang.reflect.Method)217 SimpleBeanInfo (java.beans.SimpleBeanInfo)167 FakeFox01BeanInfo (org.apache.harmony.beans.tests.support.mock.FakeFox01BeanInfo)161 IndexedPropertyDescriptor (java.beans.IndexedPropertyDescriptor)148 IntrospectionException (java.beans.IntrospectionException)115 InvocationTargetException (java.lang.reflect.InvocationTargetException)38 HashMap (java.util.HashMap)33 Test (org.junit.jupiter.api.Test)33 ArrayList (java.util.ArrayList)30 Field (java.lang.reflect.Field)17 Map (java.util.Map)17 Test (org.junit.Test)13 EventSetDescriptor (java.beans.EventSetDescriptor)12 MethodDescriptor (java.beans.MethodDescriptor)12 List (java.util.List)11 BeanDescriptor (java.beans.BeanDescriptor)10 HashSet (java.util.HashSet)8 Introspector (java.beans.Introspector)7