java.beans.PropertyDescriptor Java Examples

The following examples show how to use java.beans.PropertyDescriptor. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GenSwingBeanInfo.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Sets properties from the BeanInfo supplement on the
 * introspected PropertyDescriptor
 */
private void setDocInfoProps(DocBeanInfo dbi, PropertyDescriptor pds) {
    int beanflags = dbi.beanflags;

    if ((beanflags & DocBeanInfo.BOUND) != 0)
        pds.setBound(true);
    if ((beanflags & DocBeanInfo.EXPERT) != 0)
        pds.setExpert(true);
    if ((beanflags & DocBeanInfo.CONSTRAINED) != 0)
        pds.setConstrained(true);
    if ((beanflags & DocBeanInfo.HIDDEN) !=0)
        pds.setHidden(true);
    if ((beanflags & DocBeanInfo.PREFERRED) !=0)
        pds.setPreferred(true);

    if (!(dbi.desc.equals("null"))){
        pds.setShortDescription(dbi.desc);
    }
    if (!(dbi.displayname.equals("null"))){
        pds.setDisplayName(dbi.displayname);
    }
}
 
Example #2
Source File: Test7192955.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws IntrospectionException {
    if (!BeanUtils.findPropertyDescriptor(MyBean.class, "test").isBound()) {
        throw new Error("a simple property is not bound");
    }
    if (!BeanUtils.findPropertyDescriptor(MyBean.class, "list").isBound()) {
        throw new Error("a generic property is not bound");
    }
    if (!BeanUtils.findPropertyDescriptor(MyBean.class, "readOnly").isBound()) {
        throw new Error("a read-only property is not bound");
    }
    PropertyDescriptor[] pds = Introspector.getBeanInfo(MyBean.class, BaseBean.class).getPropertyDescriptors();
    for (PropertyDescriptor pd : pds) {
        if (pd.getName().equals("test") && pd.isBound()) {
            throw new Error("a simple property is bound without superclass");
        }
    }
}
 
Example #3
Source File: ConfigBeanImpl.java    From waterdrop with Apache License 2.0 6 votes vote down vote up
private static boolean hasAtLeastOneBeanProperty(Class<?> clazz) {
    BeanInfo beanInfo = null;
    try {
        beanInfo = Introspector.getBeanInfo(clazz);
    } catch (IntrospectionException e) {
        return false;
    }

    for (PropertyDescriptor beanProp : beanInfo.getPropertyDescriptors()) {
        if (beanProp.getReadMethod() != null && beanProp.getWriteMethod() != null) {
            return true;
        }
    }

    return false;
}
 
Example #4
Source File: BeanUtil.java    From SpringBoot2.0 with Apache License 2.0 6 votes vote down vote up
public static Map<String, Object> transBeanToMap(Object obj) {
    if (obj == null) {
        return null;
    }
    Map<String, Object> map = new HashMap<>();
    try {
        PropertyDescriptor[] propertyDescriptors = getPropertyDescriptors(obj);
        for (PropertyDescriptor property : propertyDescriptors) {
            String key = property.getName();
            // 过滤class属性
            if (!key.equals("class")) {
                // 得到property对应的getter方法
                Method getter = property.getReadMethod();
                Object value = getter.invoke(obj);
                map.put(key, value);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return map;
}
 
Example #5
Source File: BeanHelper.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Return the Class of the property if it can be determined.
 * @param bean The bean containing the property.
 * @param propName The name of the property.
 * @return The class associated with the property or null.
 */
private static Class<?> getDefaultClass(final Object bean, final String propName)
{
    try
    {
        final PropertyDescriptor desc =
                BEAN_UTILS_BEAN.getPropertyUtils().getPropertyDescriptor(
                        bean, propName);
        if (desc == null)
        {
            return null;
        }
        return desc.getPropertyType();
    }
    catch (final Exception ex)
    {
        return null;
    }
}
 
Example #6
Source File: CommonPropertyValueSetter.java    From onetwo with Apache License 2.0 6 votes vote down vote up
protected void copyArray(SimpleBeanCopier beanCopier, BeanWrapper targetBeanWrapper, Class<?> propertyType, Cloneable cloneable, PropertyDescriptor toProperty, Object srcValue){
		Assert.isTrue(propertyType==srcValue.getClass(), "property type is not equals srcValue type");
		int length = Array.getLength(srcValue);
		Object array = Array.newInstance(propertyType.getComponentType(), length);
		
		if(isContainerValueCopyValueOrRef(cloneable, srcValue)){
			for (int i = 0; i < length; i++) {
				Array.set(array, i, Array.get(srcValue, i));
			}
		}else{
			for (int i = 0; i < length; i++) {
//				Object targetElement = newBeanCopier(propertyType.getComponentType()).fromObject(Array.get(array, i));
				Object targetElement = beanCopier.fromObject(Array.get(array, i), propertyType.getComponentType());
				Array.set(array, i, targetElement);
			}
		}
//		targetBeanWrapper.setPropertyValue(toProperty.getName(), array);
		setPropertyValue0(targetBeanWrapper, toProperty.getName(), array);
	}
 
Example #7
Source File: BeanUtils.java    From danyuan-application with Apache License 2.0 6 votes vote down vote up
public static void transMap2Bean(Map<String, Object> map, Object obj) {

		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

			for (PropertyDescriptor property : propertyDescriptors) {
				String key = property.getName();

				if (map.containsKey(key)) {
					Object value = map.get(key);
					// 得到property对应的setter方法
					Method setter = property.getWriteMethod();
					setter.invoke(obj, value);
				}

			}

		} catch (Exception e) {
			System.out.println("transMap2Bean Error " + e);
		}

		return;

	}
 
Example #8
Source File: Test4634390.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private static void test(Class type) {
    for (PropertyDescriptor pd : BeanUtils.getPropertyDescriptors(type)) {
        PropertyDescriptor pdCopy = create(pd);
        if (pdCopy != null) {
            // XXX - hack! The Introspector will set the bound property
            // since it assumes that propertyChange event set descriptors
            // infers that all the properties are bound
            pdCopy.setBound(pd.isBound());

            String name = pd.getName();
            System.out.println(" - " + name);

            if (!compare(pd, pdCopy))
                throw new Error("property delegates are not equal");

            if (!pd.equals(pdCopy))
                throw new Error("equals() failed");

            if (pd.hashCode() != pdCopy.hashCode())
                throw new Error("hashCode() failed");
        }
    }
}
 
Example #9
Source File: IntrospectorTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void test_MixedSimpleClass30() throws Exception {
    BeanInfo info = Introspector.getBeanInfo(MixedSimpleClass30.class);
    Method indexedGetter = MixedSimpleClass30.class.getDeclaredMethod(
            "getList", int.class);

    for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
        if (propertyName.equals(pd.getName())) {
            assertTrue(pd instanceof IndexedPropertyDescriptor);
            assertNull(pd.getReadMethod());
            assertNull(pd.getWriteMethod());
            assertEquals(indexedGetter, ((IndexedPropertyDescriptor) pd)
                    .getIndexedReadMethod());
            assertNull(((IndexedPropertyDescriptor) pd)
                    .getIndexedWriteMethod());

        }
    }
}
 
Example #10
Source File: ReflectUtil.java    From mPaaS with Apache License 2.0 6 votes vote down vote up
/**
 * 获取bean的字段值
 */
@SuppressWarnings("unchecked")
public static <T> T getProperty(Object bean, String prop)
        throws ReflectiveOperationException {
    if (bean == null) {
        return null;
    }
    if (bean instanceof Map<?, ?>) {
        return (T) ((Map<?, ?>) bean).get(prop);
    }
    PropertyDescriptor desc = BeanUtils
            .getPropertyDescriptor(bean.getClass(), prop);
    if (desc == null) {
        throw new NoSuchFieldException();
    }
    Method method = desc.getReadMethod();
    if (method == null) {
        throw new NoSuchMethodException();
    }
    return (T) method.invoke(bean);
}
 
Example #11
Source File: Test4634390.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private static PropertyDescriptor create(PropertyDescriptor pd) {
    try {
        if (pd instanceof IndexedPropertyDescriptor) {
            IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor) pd;
            return new IndexedPropertyDescriptor(
                    ipd.getName(),
                    ipd.getReadMethod(),
                    ipd.getWriteMethod(),
                    ipd.getIndexedReadMethod(),
                    ipd.getIndexedWriteMethod());
        } else {
            return new PropertyDescriptor(
                    pd.getName(),
                    pd.getReadMethod(),
                    pd.getWriteMethod());
        }
    }
    catch (IntrospectionException exception) {
        exception.printStackTrace();
        return null;
    }
}
 
Example #12
Source File: MessageDecoder.java    From jt808-server with Apache License 2.0 6 votes vote down vote up
public <T> T decode(ByteBuf buf, Class<T> targetClass) {
    T result = BeanUtils.newInstance(targetClass);

    PropertyDescriptor[] pds = getPropertyDescriptor(targetClass);
    for (PropertyDescriptor pd : pds) {

        Method readMethod = pd.getReadMethod();
        Property prop = readMethod.getDeclaredAnnotation(Property.class);
        int length = getLength(result, prop);
        if (!buf.isReadable(length))
            break;

        if (length == -1)
            length = buf.readableBytes();
        Object value = null;
        try {
            value = read(buf, prop, length, pd);
        } catch (Exception e) {
            e.printStackTrace();
        }
        BeanUtils.setValue(result, pd.getWriteMethod(), value);
    }
    return result;
}
 
Example #13
Source File: IntrospectorTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void test_MixedBooleanSimpleClass11() throws Exception {
    BeanInfo info = Introspector
            .getBeanInfo(MixedBooleanSimpleClass11.class);
    Method setter = MixedBooleanSimpleClass11.class.getDeclaredMethod(
            "setList", int.class, boolean.class);

    for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
        if (propertyName.equals(pd.getName())) {
            assertTrue(pd instanceof IndexedPropertyDescriptor);
            assertNull(pd.getReadMethod());
            assertNull(pd.getWriteMethod());
            assertNull(((IndexedPropertyDescriptor) pd)
                    .getIndexedReadMethod());
            assertEquals(setter, ((IndexedPropertyDescriptor) pd)
                    .getIndexedWriteMethod());
        }
    }
}
 
Example #14
Source File: JButtonBarBeanInfo.java    From orbit-image-analysis with GNU General Public License v3.0 6 votes vote down vote up
/**
  * Gets the Property Descriptors
  *
  * @return   The propertyDescriptors value
  */
 public PropertyDescriptor[] getPropertyDescriptors() 
 {
    try
    {
       Vector descriptors = new Vector();
       PropertyDescriptor descriptor = null;

       return (PropertyDescriptor[]) descriptors.toArray(new PropertyDescriptor[descriptors.size()]);
    }
    catch (Exception e)
    {
       // do not ignore, bomb politely so use has chance to discover what went wrong...
// I know that this is suboptimal solution, but swallowing silently is
// even worse... Propose better solution! 
e.printStackTrace();
    }
    return null;
 }
 
Example #15
Source File: AssetSeparatePaymentDistributor.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Utility method which can take one payment and distribute its amount by ratio to the target payments
 * 
 * @param source Source Payment
 * @param targets Target Payment
 * @param ratios Ratio to be applied for each target
 */
private void applyRatioToPaymentAmounts(AssetPayment source, AssetPayment[] targets, double[] ratios) {
    try {
        for (PropertyDescriptor propertyDescriptor : assetPaymentProperties) {
            Method readMethod = propertyDescriptor.getReadMethod();
            if (readMethod != null && propertyDescriptor.getPropertyType() != null && KualiDecimal.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
                KualiDecimal amount = (KualiDecimal) readMethod.invoke(source);
                if (amount != null && amount.isNonZero()) {
                    KualiDecimal[] ratioAmounts = KualiDecimalUtils.allocateByRatio(amount, ratios);
                    Method writeMethod = propertyDescriptor.getWriteMethod();
                    if (writeMethod != null) {
                        for (int i = 0; i < ratioAmounts.length; i++) {
                            writeMethod.invoke(targets[i], ratioAmounts[i]);
                        }
                    }
                }
            }
        }
    }
    catch (Exception e) {
        throw new RuntimeException(e);
    }

}
 
Example #16
Source File: IntrospectorTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void test_MixedBooleanExtendClass12() throws Exception {
    BeanInfo info = Introspector
            .getBeanInfo(MixedBooleanExtendClass12.class);
    Method getter = MixedBooleanSimpleClass41.class
            .getDeclaredMethod("getList");
    Method setter = MixedBooleanSimpleClass41.class.getDeclaredMethod(
            "setList", boolean.class);

    for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
        if (propertyName.equals(pd.getName())) {
            assertFalse(pd instanceof IndexedPropertyDescriptor);
            assertEquals(getter, pd.getReadMethod());
            assertEquals(setter, pd.getWriteMethod());
        }
    }
}
 
Example #17
Source File: AbstractArmeriaBeanPostProcessor.java    From armeria with Apache License 2.0 6 votes vote down vote up
private LocalArmeriaPortElement(Member member, AnnotatedElement ae, @Nullable PropertyDescriptor pd) {
    super(member, pd);
    final LocalArmeriaPort localArmeriaPort = ae.getAnnotation(LocalArmeriaPort.class);
    final SessionProtocol protocol = localArmeriaPort.value();
    Server server = getServer();
    if (server == null) {
        server = beanFactory.getBean(Server.class);
        serServer(server);
    }

    Integer port = portCache.get(protocol);
    if (port == null) {
        port = server.activeLocalPort(protocol);
        portCache.put(protocol, port);
    }
    this.port = port;
}
 
Example #18
Source File: PropertyUtilsTestCase.java    From commons-beanutils with Apache License 2.0 6 votes vote down vote up
/**
 * Positive test for getPropertyDescriptors().  Each property name
 * listed in {@code properties} should be returned exactly once.
 */
public void testGetDescriptors() {

    final PropertyDescriptor[] pd =
            PropertyUtils.getPropertyDescriptors(bean);
    assertNotNull("Got descriptors", pd);
    final int[] count = new int[properties.length];
    for (final PropertyDescriptor element : pd) {
        final String name = element.getName();
        for (int j = 0; j < properties.length; j++) {
            if (name.equals(properties[j])) {
                count[j]++;
            }
        }
    }
    for (int j = 0; j < properties.length; j++) {
        if (count[j] < 0) {
            fail("Missing property " + properties[j]);
        } else if (count[j] > 1) {
            fail("Duplicate property " + properties[j]);
        }
    }

}
 
Example #19
Source File: MetadataMBeanInfoAssembler.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a description for the attribute corresponding to this property
 * descriptor. Attempts to create the description using metadata from either
 * the getter or setter attributes, otherwise uses the property name.
 */
@Override
protected String getAttributeDescription(PropertyDescriptor propertyDescriptor, String beanKey) {
	Method readMethod = propertyDescriptor.getReadMethod();
	Method writeMethod = propertyDescriptor.getWriteMethod();

	ManagedAttribute getter =
			(readMethod != null ? this.attributeSource.getManagedAttribute(readMethod) : null);
	ManagedAttribute setter =
			(writeMethod != null ? this.attributeSource.getManagedAttribute(writeMethod) : null);

	if (getter != null && StringUtils.hasText(getter.getDescription())) {
		return getter.getDescription();
	}
	else if (setter != null && StringUtils.hasText(setter.getDescription())) {
		return setter.getDescription();
	}

	ManagedMetric metric = (readMethod != null ? this.attributeSource.getManagedMetric(readMethod) : null);
	if (metric != null && StringUtils.hasText(metric.getDescription())) {
		return metric.getDescription();
	}

	return propertyDescriptor.getDisplayName();
}
 
Example #20
Source File: PropertyUtil.java    From activejpa with Apache License 2.0 5 votes vote down vote up
public static Method getReadMethod(Object bean, String name) {
	try {
		Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass("org.apache.commons.beanutils.PropertyUtils");
		Method method = clazz.getMethod("getPropertyDescriptor", Object.class, String.class);
		Object descriptor = method.invoke(null, bean, name);
		if (descriptor == null) {
			throw new ActiveJpaException("Property descriptor not found for the field - " + name);
		}
		method = clazz.getMethod("getReadMethod", PropertyDescriptor.class);
		return (Method) method.invoke(null, descriptor);
	} catch (Exception e) {
		throw new ActiveJpaException("Failed while getting the property descriptor", e);
	}
}
 
Example #21
Source File: Test7193977.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public AbstractBeanInfo() throws IntrospectionException {
    super(Abstract.class);
    for (PropertyDescriptor pd : getPropertyDescriptors()) {
        if (names.contains(pd.getName())) {
            pd.setValue("transient", Boolean.TRUE);
        }
    }
}
 
Example #22
Source File: CachedIntrospectionResults.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
PropertyDescriptor[] getPropertyDescriptors() {
	PropertyDescriptor[] pds = new PropertyDescriptor[this.propertyDescriptorCache.size()];
	int i = 0;
	for (PropertyDescriptor pd : this.propertyDescriptorCache.values()) {
		pds[i] = (pd instanceof GenericTypeAwarePropertyDescriptor ? pd :
				buildGenericTypeAwarePropertyDescriptor(getBeanClass(), pd));
		i++;
	}
	return pds;
}
 
Example #23
Source File: QueryGenerator.java    From jeecg-cloud with Apache License 2.0 5 votes vote down vote up
/**
 *   根据权限相关配置生成相关的SQL 语句
 * @param clazz
 * @return
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static String installAuthJdbc(Class<?> clazz) {
	StringBuffer sb = new StringBuffer();
	//权限查询
	Map<String,SysPermissionDataRuleModel> ruleMap = getRuleMap();
	PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(clazz);
	String sql_and = " and ";
	for (String c : ruleMap.keySet()) {
		if(oConvertUtils.isNotEmpty(c) && c.startsWith(SQL_RULES_COLUMN)){
			sb.append(sql_and+getSqlRuleValue(ruleMap.get(c).getRuleValue()));
		}
	}
	String name;
	for (int i = 0; i < origDescriptors.length; i++) {
		name = origDescriptors[i].getName();
		if (judgedIsUselessField(name)) {
			continue;
		}
		if(ruleMap.containsKey(name)) {
			SysPermissionDataRuleModel dataRule = ruleMap.get(name);
			QueryRuleEnum rule = QueryRuleEnum.getByValue(dataRule.getRuleConditions());
			Class propType = origDescriptors[i].getPropertyType();
			boolean isString = propType.equals(String.class);
			Object value;
			if(isString) {
				value = converRuleValue(dataRule.getRuleValue());
			}else {
				value = NumberUtils.parseNumber(dataRule.getRuleValue(),propType);
			}
			String filedSql = getSingleSqlByRule(rule, oConvertUtils.camelToUnderline(name), value,isString);
			sb.append(sql_and+filedSql);
		}
	}
	log.info("query auth sql is:"+sb.toString());
	return sb.toString();
}
 
Example #24
Source File: BeanUtils.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Reports all the interesting information in an Indexed/PropertyDescrptor.
 */
public static void reportPropertyDescriptor(PropertyDescriptor pd) {
    System.out.println("property name:  " + pd.getName());
    System.out.println("         type:  " + pd.getPropertyType());
    System.out.println("         read:  " + pd.getReadMethod());
    System.out.println("         write: " + pd.getWriteMethod());
    if (pd instanceof IndexedPropertyDescriptor) {
        IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor) pd;
        System.out.println(" indexed type: " + ipd.getIndexedPropertyType());
        System.out.println(" indexed read: " + ipd.getIndexedReadMethod());
        System.out.println(" indexed write: " + ipd.getIndexedWriteMethod());
    }
}
 
Example #25
Source File: AdvancedPropertyUtils.java    From waggle-dance with Apache License 2.0 5 votes vote down vote up
private synchronized boolean include(Property property) {
  boolean eligible = property.isReadable() && (allowReadOnlyProperties || property.isWritable());
  if (!eligible) {
    return false;
  }
  if (MethodProperty.class.isAssignableFrom(property.getClass())) {
    PropertyDescriptor propertyDescriptor = getPropertyDescriptor((MethodProperty) property);
    return propertyDescriptor == null || !isTransient(propertyDescriptor);
  }
  return true;
}
 
Example #26
Source File: PropertyDescriptorTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testPropertyDescriptorStringClass_PropertyNameEmpty()
        throws IntrospectionException {
    String propertyName = "";
    Class<MockJavaBean> beanClass = MockJavaBean.class;
    try {
        new PropertyDescriptor(propertyName, beanClass);
        fail("Should throw IntrospectionException.");
    } catch (IntrospectionException exception) {
    }
}
 
Example #27
Source File: Test8027648.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static Class<?> getPropertyType(Class<?> type, boolean indexed) {
    PropertyDescriptor pd = BeanUtils.findPropertyDescriptor(type, indexed ? "index" : "value");
    if (pd instanceof IndexedPropertyDescriptor) {
        IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor) pd;
        return ipd.getIndexedPropertyType();
    }
    return pd.getPropertyType();
}
 
Example #28
Source File: ReflectionUtils.java    From spring-data-simpledb with MIT License 5 votes vote down vote up
private static <T> Method retrieveGetterFrom(final Class<T> entityClazz, final String fieldName) {
	Method getterMethod;
	try {
		final PropertyDescriptor descriptor = new PropertyDescriptor(fieldName, entityClazz);
		getterMethod = descriptor.getReadMethod();
	} catch(IntrospectionException e) {
		getterMethod = null;
		LOG.debug("Field {} has not declared getter method", fieldName, e);
	}
	return getterMethod;
}
 
Example #29
Source File: Test4634390.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static boolean compare(PropertyDescriptor pd1, PropertyDescriptor pd2) {
    if (!compare(pd1.getReadMethod(), pd2.getReadMethod())) {
        System.out.println("read methods not equal");
        return false;
    }
    if (!compare(pd1.getWriteMethod(), pd2.getWriteMethod())) {
        System.out.println("write methods not equal");
        return false;
    }
    if (pd1.getPropertyType() != pd2.getPropertyType()) {
        System.out.println("property type not equal");
        return false;
    }
    if (pd1.getPropertyEditorClass() != pd2.getPropertyEditorClass()) {
        System.out.println("property editor class not equal");
        return false;
    }
    if (pd1.isBound() != pd2.isBound()) {
        System.out.println("bound value not equal");
        return false;
    }
    if (pd1.isConstrained() != pd2.isConstrained()) {
        System.out.println("constrained value not equal");
        return false;
    }
    return true;
}
 
Example #30
Source File: FinderType.java    From gyro with Apache License 2.0 5 votes vote down vote up
private FinderType(Class<F> finderClass) {
    this.finderClass = finderClass;
    this.name = Reflections.getNamespace(finderClass) + "::" + Reflections.getType(finderClass);

    ImmutableList.Builder<FinderField> fields = ImmutableList.builder();
    ImmutableMap.Builder<String, FinderField> fieldByJavaName = ImmutableMap.builder();
    ImmutableMap.Builder<String, FinderField> fieldByGyroName = ImmutableMap.builder();

    for (PropertyDescriptor prop : Reflections.getBeanInfo(finderClass).getPropertyDescriptors()) {
        Method getter = prop.getReadMethod();
        Method setter = prop.getWriteMethod();

        if (getter != null && setter != null) {
            java.lang.reflect.Type getterType = getter.getGenericReturnType();
            java.lang.reflect.Type setterType = setter.getGenericParameterTypes()[0];

            if (getterType.equals(setterType)) {
                FinderField field = new FinderField(prop.getName(), getter, setter, getterType);

                fields.add(field);
                fieldByJavaName.put(field.getJavaName(), field);
                fieldByGyroName.put(field.getGyroName(), field);
            }
        }
    }

    this.fields = fields.build();
    this.fieldByJavaName = fieldByJavaName.build();
    this.fieldByGyroName = fieldByGyroName.build();
}