001 /*
002 GRANITE DATA SERVICES
003 Copyright (C) 2012 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
021 package org.granite.client.util;
022
023 import java.beans.Introspector;
024 import java.beans.PropertyDescriptor;
025 import java.lang.reflect.Field;
026 import java.lang.reflect.Method;
027 import java.lang.reflect.Modifier;
028
029 /**
030 * @author Franck WOLFF
031 */
032 public abstract class BeanUtil {
033
034 public static PropertyDescriptor[] getProperties(Class<?> clazz) {
035 try {
036 PropertyDescriptor[] properties = Introspector.getBeanInfo(clazz).getPropertyDescriptors();
037 Field[] fields = clazz.getDeclaredFields();
038 for (Field field : fields) {
039 if (Boolean.class.equals(field.getType())) {
040 boolean found = false;
041 for (PropertyDescriptor property : properties) {
042 if (property.getName().equals(field.getName())) {
043 found = true;
044 if (property.getReadMethod() == null) {
045 try {
046 Method readMethod = clazz.getDeclaredMethod(getIsMethodName(field.getName()));
047 if (Modifier.isPublic(readMethod.getModifiers()) && !Modifier.isStatic(readMethod.getModifiers()))
048 property.setReadMethod(readMethod);
049 }
050 catch (NoSuchMethodException e) {
051 }
052 }
053 break;
054 }
055 }
056 if (!found) {
057 try {
058 Method readMethod = clazz.getDeclaredMethod(getIsMethodName(field.getName()));
059 if (Modifier.isPublic(readMethod.getModifiers()) && !Modifier.isStatic(readMethod.getModifiers())) {
060 PropertyDescriptor[] propertiesTmp = new PropertyDescriptor[properties.length + 1];
061 System.arraycopy(properties, 0, propertiesTmp, 0, properties.length);
062 propertiesTmp[properties.length] = new PropertyDescriptor(field.getName(), readMethod, null);
063 properties = propertiesTmp;
064 }
065 }
066 catch (NoSuchMethodException e) {
067 }
068 }
069 }
070 }
071 return properties;
072 } catch (Exception e) {
073 throw new RuntimeException("Could not introspect properties of class: " + clazz, e);
074 }
075 }
076
077 private static String getIsMethodName(String name) {
078 return "is" + name.substring(0, 1).toUpperCase() + name.substring(1);
079 }
080 }