001 /**
002 * GRANITE DATA SERVICES
003 * Copyright (C) 2006-2013 GRANITE DATA SERVICES S.A.S.
004 *
005 * This file is part of Granite Data Services.
006 *
007 * Granite Data Services is free software; you can redistribute it and/or modify
008 * it under the terms of the GNU Library General Public License as published by
009 * the Free Software Foundation; either version 2 of the License, or (at your
010 * option) any later version.
011 *
012 * Granite Data Services is distributed in the hope that it will be useful, but
013 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
014 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
015 * for more details.
016 *
017 * You should have received a copy of the GNU Library General Public License
018 * along with this library; if not, see <http://www.gnu.org/licenses/>.
019 */
020 package org.granite.client.util;
021
022 import java.beans.Introspector;
023 import java.beans.PropertyDescriptor;
024 import java.lang.reflect.Field;
025 import java.lang.reflect.Method;
026 import java.lang.reflect.Modifier;
027
028 /**
029 * @author Franck WOLFF
030 */
031 public abstract class BeanUtil {
032
033 public static PropertyDescriptor[] getProperties(Class<?> clazz) {
034 try {
035 PropertyDescriptor[] properties = Introspector.getBeanInfo(clazz).getPropertyDescriptors();
036 Field[] fields = clazz.getDeclaredFields();
037 for (Field field : fields) {
038 if (Boolean.class.equals(field.getType())) {
039 boolean found = false;
040 for (PropertyDescriptor property : properties) {
041 if (property.getName().equals(field.getName())) {
042 found = true;
043 if (property.getReadMethod() == null) {
044 try {
045 Method readMethod = clazz.getDeclaredMethod(getIsMethodName(field.getName()));
046 if (Modifier.isPublic(readMethod.getModifiers()) && !Modifier.isStatic(readMethod.getModifiers()))
047 property.setReadMethod(readMethod);
048 }
049 catch (NoSuchMethodException e) {
050 }
051 }
052 break;
053 }
054 }
055 if (!found) {
056 try {
057 Method readMethod = clazz.getDeclaredMethod(getIsMethodName(field.getName()));
058 if (Modifier.isPublic(readMethod.getModifiers()) && !Modifier.isStatic(readMethod.getModifiers())) {
059 PropertyDescriptor[] propertiesTmp = new PropertyDescriptor[properties.length + 1];
060 System.arraycopy(properties, 0, propertiesTmp, 0, properties.length);
061 propertiesTmp[properties.length] = new PropertyDescriptor(field.getName(), readMethod, null);
062 properties = propertiesTmp;
063 }
064 }
065 catch (NoSuchMethodException e) {
066 }
067 }
068 }
069 }
070 return properties;
071 } catch (Exception e) {
072 throw new RuntimeException("Could not introspect properties of class: " + clazz, e);
073 }
074 }
075
076 private static String getIsMethodName(String name) {
077 return "is" + name.substring(0, 1).toUpperCase() + name.substring(1);
078 }
079 }