Java Code Examples for java.beans.Introspector

The following are top voted examples for showing how to use java.beans.Introspector. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: jdk8u-jdk   File: TestBeanInfo.java   View source code 7 votes vote down vote up
public void run() {
    Introspector.flushCaches();

    test(FirstBean.class, FirstBeanBeanInfo.class);
    test(SecondBean.class, null);
    test(ThirdBean.class, null);
    test(ThirdBeanBeanInfo.class, ThirdBeanBeanInfo.class);

    Introspector.setBeanInfoSearchPath(SEARCH_PATH);
    Introspector.flushCaches();

    test(FirstBean.class, FirstBeanBeanInfo.class);
    test(SecondBean.class, SecondBeanBeanInfo.class);
    test(ThirdBean.class, null);
    test(ThirdBeanBeanInfo.class, ThirdBeanBeanInfo.class);
}
 
Example 2
Project: ares   File: ReflectionManager.java   View source code 7 votes vote down vote up
/**
 * Maps object attributes.
 * @param type the class to reflect.
 * @param object the instance to address.
 * @param <T> the class to reflect.
 * @return the attributes mapping.
 * @throws IntrospectionException when errors in reflection.
 * @throws InvocationTargetException when errors in reflection.
 * @throws IllegalAccessException when errors in reflection.
 */
public static <T> Map<String,Object> getAttributes(Class<T> type, T object)
    throws IntrospectionException, InvocationTargetException, IllegalAccessException {
  Map<String,Object> propsmap = new HashMap<>();
  final BeanInfo beanInfo = Introspector.getBeanInfo(type);
  final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
  for (PropertyDescriptor pd : propertyDescriptors) {
    if (pd.getName().equals("class")) continue;
    final Method getter = pd.getReadMethod();
    if (getter != null) {
      final String attrname = pd.getName();
      final Object attrvalue = getter.invoke(object);
      propsmap.put(attrname, attrvalue);
    }
  }
  return propsmap;
}
 
Example 3
Project: jdk8u-jdk   File: TestIntrospector.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws IntrospectionException {
    StringBuilder sb = null;
    if (args.length > 0) {
        if (args[0].equals("show")) {
            sb = new StringBuilder(65536);
        }
    }
    Introspector.flushCaches();
    int count = (sb != null) ? 10 : 100;
    long time = -System.currentTimeMillis();
    for (int i = 0; i < count; i++) {
        test(sb);
        test(sb);
        Introspector.flushCaches();
    }
    time += System.currentTimeMillis();
    System.out.println("Time (average): " + time / count);
}
 
Example 4
Project: bubichain-sdk-java   File: PojoPropertiesConverter.java   View source code 6 votes vote down vote up
private void resolveParamProperties() throws IntrospectionException{
    List<ArgDefEntry<RequestParamDefinition>> reqParamDefs = new LinkedList<>();

    BeanInfo beanInfo = Introspector.getBeanInfo(argType);
    PropertyDescriptor[] propDescs = beanInfo.getPropertyDescriptors();

    for (PropertyDescriptor propDesc : propDescs) {
        //            TypeDescriptor propTypeDesc;
        //            propTypeDesc = beanWrapper.getPropertyTypeDescriptor(propDesc.getName());


        //            RequestParam reqParamAnno = propTypeDesc.getAnnotation(RequestParam.class);
        RequestParam reqParamAnno = propDesc.getPropertyType().getAnnotation(RequestParam.class);
        if (reqParamAnno == null) {
            // 忽略未标注 RequestParam 的属性;
            continue;
        }
        RequestParamDefinition reqParamDef = RequestParamDefinition.resolveDefinition(reqParamAnno);
        ArgDefEntry<RequestParamDefinition> defEntry = new ArgDefEntry<>(reqParamDefs.size(), propDesc.getPropertyType(),
                reqParamDef);
        reqParamDefs.add(defEntry);
        propNames.add(propDesc.getName());
    }
    paramResolver = RequestParamResolvers.createParamResolver(reqParamDefs);
}
 
Example 5
Project: parabuild-ci   File: H3BeanConverter.java   View source code 6 votes vote down vote up
/**
 * Cache the method if possible, using the classname and property name to
 * allow for similar named methods.
 * @param data The bean to introspect
 * @param property The property to get the accessor for
 * @return The getter method
 * @throws IntrospectionException
 */
protected Method findGetter(Object data, String property) throws IntrospectionException
{
    String key = data.getClass().getName() + ":" + property;

    Method method = (Method) methods.get(key);
    if (method == null)
    {
        PropertyDescriptor[] props = Introspector.getBeanInfo(data.getClass()).getPropertyDescriptors();
        for (int i = 0; i < props.length; i++)
        {
            if (props[i].getName().equalsIgnoreCase(property))
            {
                method = props[i].getReadMethod();
            }
        }

        methods.put(key, method);
    }

    return method;
}
 
Example 6
Project: incubator-netbeans   File: ObjectEditor.java   View source code 6 votes vote down vote up
private String getDescription (Lookup.Item item) {
    String id = item.getId ();
    String result = null;
    try {
        result = Introspector.getBeanInfo(item.getInstance().getClass()).getBeanDescriptor().getShortDescription();
    } catch (IntrospectionException ie) {
        //do nothing
    }
    String toCheck = item.getInstance().getClass().getName();
    toCheck = toCheck.lastIndexOf('.')!=-1 ? 
        toCheck.substring(toCheck.lastIndexOf('.')+1) : toCheck; //NOI18N
    if (toCheck.equals(result)) {
        result = null;
    } 
    return result;
}
 
Example 7
Project: jdk8u-jdk   File: Test4520754.java   View source code 6 votes vote down vote up
private static BeanInfo getBeanInfo(Boolean mark, Class type) {
    System.out.println("test=" + mark + " for " + type);
    BeanInfo info;
    try {
        info = Introspector.getBeanInfo(type);
    } catch (IntrospectionException exception) {
        throw new Error("unexpected exception", exception);
    }
    if (info == null) {
        throw new Error("could not find BeanInfo for " + type);
    }
    if (mark != info.getBeanDescriptor().getValue("test")) {
        throw new Error("could not find marked BeanInfo for " + type);
    }
    return info;
}
 
Example 8
Project: incubator-netbeans   File: TmpPattern.java   View source code 6 votes vote down vote up
/** Based on names of indexedGetter and indexedSetter resolves the name
 * of the indexed property.
 * @return Name of the indexed property
 */ 
String findIndexedPropertyName() {
    String superName = findPropertyName();

    if ( superName == null ) {
        String methodName = null;

        if ( indexedGetterMethod != null )
            methodName = nameAsString(indexedGetterMethod);
        else if ( indexedSetterMethod != null )
            methodName = nameAsString(indexedSetterMethod);
        else
            throw new InternalError( "Indexed property with all methods == null" ); // NOI18N

        return methodName.startsWith( IS_PREFIX ) ? // NOI18N
               Introspector.decapitalize( methodName.substring(2) ) :
               Introspector.decapitalize( methodName.substring(3) );
    }
    else
        return superName;
}
 
Example 9
Project: incubator-netbeans   File: PropertySupport.java   View source code 6 votes vote down vote up
/** Create a support with method objects specified.
* The methods must be public.
* @param instance (Bean) object to work on
* @param valueType type of the property
* @param getter getter method, can be <code>null</code>
* @param setter setter method, can be <code>null</code>
* @throws IllegalArgumentException if the methods are not public
*/
public Reflection(Object instance, Class<T> valueType, Method getter, Method setter) {
    super(valueType);

    if ((getter != null) && !Modifier.isPublic(getter.getModifiers())) {
        throw new IllegalArgumentException("Cannot use a non-public getter " + getter); // NOI18N
    }

    if ((setter != null) && !Modifier.isPublic(setter.getModifiers())) {
        throw new IllegalArgumentException("Cannot use a non-public setter " + setter); // NOI18N
    }

    if (getter != null) {
        setName(Introspector.decapitalize(getter.getName().replaceFirst("^(get|is|has)", "")));
    } else if (setter != null) {
        setName(Introspector.decapitalize(setter.getName().replaceFirst("^set", "")));
    }

    this.instance = instance;
    this.setter = setter;
    this.getter = getter;
}
 
Example 10
Project: jdk8u-jdk   File: Test7192955.java   View source code 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 11
Project: iBase4J   File: InstanceUtil.java   View source code 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 12
Project: springbootWeb   File: RootClassInfo.java   View source code 6 votes vote down vote up
private RootClassInfo(String className, List<String> warnings) {
    super();
    this.className = className;
    this.warnings = warnings;

    if (className == null) {
        return;
    }
    
    FullyQualifiedJavaType fqjt = new FullyQualifiedJavaType(className);
    String nameWithoutGenerics = fqjt.getFullyQualifiedNameWithoutTypeParameters();
    if (!nameWithoutGenerics.equals(className)) {
        genericMode = true;
    }

    try {
        Class<?> clazz = ObjectFactory.externalClassForName(nameWithoutGenerics);
        BeanInfo bi = Introspector.getBeanInfo(clazz);
        propertyDescriptors = bi.getPropertyDescriptors();
    } catch (Exception e) {
        propertyDescriptors = null;
        warnings.add(getString("Warning.20", className)); //$NON-NLS-1$
    }
}
 
Example 13
Project: jdk8u-jdk   File: Test7195106.java   View source code 6 votes vote down vote up
public static void main(String[] arg) throws Exception {
    BeanInfo info = Introspector.getBeanInfo(My.class);
    if (null == info.getIcon(BeanInfo.ICON_COLOR_16x16)) {
        throw new Error("Unexpected behavior");
    }
    try {
        int[] array = new int[1024];
        while (true) {
            array = new int[array.length << 1];
        }
    }
    catch (OutOfMemoryError error) {
        System.gc();
    }
    if (null == info.getIcon(BeanInfo.ICON_COLOR_16x16)) {
        throw new Error("Explicit BeanInfo is collected");
    }
}
 
Example 14
Project: spring-rest-commons-options   File: ReflectionUtils.java   View source code 6 votes vote down vote up
private static void collectParameters(Collection<Parameters> parameters, Parameter parameter, Annotation a,
		boolean isPathVariable) {
	if (a != null) {
		String typeStr = parameter.getType().getSimpleName();
		Type type = parameter.getParameterizedType();
		if (type instanceof ParameterizedType) {
			typeStr = ((Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0]).getSimpleName();
		}
		parameters.add(new Parameters((boolean) AnnotationUtils.getValue(a, "required"),
				(String) (AnnotationUtils.getValue(a).equals("") ? parameter.getName()
						: AnnotationUtils.getValue(a)),
				typeStr));
	} else if (Pageable.class.isAssignableFrom(parameter.getType()) && !isPathVariable) {
		try {
			for (PropertyDescriptor propertyDescriptor : Introspector.getBeanInfo(parameter.getType())
					.getPropertyDescriptors()) {
				parameters.add(new Parameters(false, propertyDescriptor.getName(),
						propertyDescriptor.getPropertyType().getSimpleName()));
			}
		} catch (IntrospectionException e) {
			LOGGER.error("Problemas al obtener el Pageable: {}", parameter, e);
		}
	}
}
 
Example 15
Project: JAVA-   File: InstanceUtil.java   View source code 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 16
Project: openjdk-jdk10   File: Test7195106.java   View source code 6 votes vote down vote up
public static void main(String[] arg) throws Exception {
    BeanInfo info = Introspector.getBeanInfo(My.class);
    if (null == info.getIcon(BeanInfo.ICON_COLOR_16x16)) {
        throw new Error("Unexpected behavior");
    }
    try {
        int[] array = new int[1024];
        while (true) {
            array = new int[array.length << 1];
        }
    }
    catch (OutOfMemoryError error) {
        System.gc();
    }
    if (null == info.getIcon(BeanInfo.ICON_COLOR_16x16)) {
        throw new Error("Explicit BeanInfo is collected");
    }
}
 
Example 17
Project: iBase4J-Common   File: InstanceUtil.java   View source code 6 votes vote down vote up
public static Map<String, Object> transBean2Map(Object obj) {
    Map<String, Object> map = newHashMap();
    if (obj == null) {
        return map;
    }
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        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) {
        logger.error("transBean2Map Error " + e);
    }
    return map;
}
 
Example 18
Project: opencron   File: ReflectUitls.java   View source code 6 votes vote down vote up
/**
 * 
 * java反射bean的set方法
 * 
 * @param clazz
 *            javaBean对象
 * @param fieldName
 *            字段名称
 * 
 * @return set方法
 */
public static Method setter(Class<?> clazz, String fieldName) {
       AssertUtils.notNull(clazz,fieldName);
       try {
           PropertyDescriptor[] objPds = Introspector.getBeanInfo(clazz).getPropertyDescriptors();

           for (int i = 0; objPds.length > 1 && i < objPds.length; i++) {
               //跳出从object继承的class属性,源上必须有get方法
               if (Class.class == objPds[i].getPropertyType()
                       || objPds[i].getReadMethod() == null) {
                   continue;
               }

               if (objPds[i].getName().equals(fieldName)){
                   return objPds[i].getWriteMethod();
               }
           }

       } catch (IntrospectionException e) {
           throw new RuntimeException(e.getMessage());
       }

       return null;
}
 
Example 19
Project: automat   File: InstanceUtil.java   View source code 6 votes vote down vote up
public static Map<String, Object> transBean2Map(Object obj) {
    Map<String, Object> map = newHashMap();
    if (obj == null) {
        return map;
    }
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        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) {
        System.out.println("transBean2Map Error " + e);
    }
    return map;
}
 
Example 20
Project: MybatisGeneatorUtil   File: RootClassInfo.java   View source code 6 votes vote down vote up
private RootClassInfo(String className, List<String> warnings) {
    super();
    this.className = className;
    this.warnings = warnings;

    if (className == null) {
        return;
    }
    
    FullyQualifiedJavaType fqjt = new FullyQualifiedJavaType(className);
    String nameWithoutGenerics = fqjt.getFullyQualifiedNameWithoutTypeParameters();
    if (!nameWithoutGenerics.equals(className)) {
        genericMode = true;
    }

    try {
        Class<?> clazz = ObjectFactory.externalClassForName(nameWithoutGenerics);
        BeanInfo bi = Introspector.getBeanInfo(clazz);
        propertyDescriptors = bi.getPropertyDescriptors();
    } catch (Exception e) {
        propertyDescriptors = null;
        warnings.add(getString("Warning.20", className)); //$NON-NLS-1$
    }
}
 
Example 21
Project: JAVA-   File: InstanceUtil.java   View source code 6 votes vote down vote up
public static Map<String, Object> transBean2Map(Object obj) {
    Map<String, Object> map = newHashMap();
    if (obj == null) {
        return map;
    }
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        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) {
        System.out.println("transBean2Map Error " + e);
    }
    return map;
}
 
Example 22
Project: CodeGen   File: BuilderUtil.java   View source code 6 votes vote down vote up
/**
 * Bean --> Map
 * @param obj
 * @return
 */
public static Map<String, Object> transBean2Map(Object obj) {
    if(obj == null){
        return null;
    }
    Map<String, Object> map = new HashMap<>();
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            String key = property.getName();
            // 过滤class属性
            if (!"class".equals(key)) {
                // 得到property对应的getter方法
                Method getter = property.getReadMethod();
                Object value = getter.invoke(obj);
                map.put(key, value);
            }
        }
    } catch (Exception e) {
        System.out.println("transBean2Map Error " + e);
    }
    return map;
}
 
Example 23
Project: gate-core   File: CorpusAnnotationDiff.java   View source code 6 votes vote down vote up
/**
 * Sets the value for a specified parameter.
 *
 * @param paramaterName the name for the parameteer
 * @param parameterValue the value the parameter will receive
 */
@Override
public void setParameterValue(String paramaterName, Object parameterValue)
            throws ResourceInstantiationException{
  // get the beaninfo for the resource bean, excluding data about Object
  BeanInfo resBeanInf = null;
  try {
    resBeanInf = Introspector.getBeanInfo(this.getClass(), Object.class);
  } catch(Exception e) {
    throw new ResourceInstantiationException(
      "Couldn't get bean info for resource " + this.getClass().getName()
      + Strings.getNl() + "Introspector exception was: " + e
    );
  }
  AbstractResource.setParameterValue(this, resBeanInf, paramaterName, parameterValue);
}
 
Example 24
Project: neoscada   File: AbstractObjectExporter.java   View source code 6 votes vote down vote up
/**
 * create data items from the properties
 */
protected void createDataItems ( final Class<?> targetClazz )
{
    try
    {
        final BeanInfo bi = Introspector.getBeanInfo ( targetClazz );
        for ( final PropertyDescriptor pd : bi.getPropertyDescriptors () )
        {
            final DataItem item = createItem ( pd, targetClazz );
            this.items.put ( pd.getName (), item );

            final Map<String, Variant> itemAttributes = new HashMap<String, Variant> ();
            fillAttributes ( pd, itemAttributes );
            this.attributes.put ( pd.getName (), itemAttributes );

            initAttribute ( pd );
        }
    }
    catch ( final IntrospectionException e )
    {
        logger.info ( "Failed to read initial item", e );
    }
}
 
Example 25
Project: openjdk-jdk10   File: InheritPropertyInfoTest.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        BeanInfo i = Introspector.getBeanInfo(C.class, Object.class);
        PropertyDescriptor[] pds = i.getPropertyDescriptors();

        Checker.checkEq("number of properties", pds.length, 1);
        PropertyDescriptor p = pds[0];

        Checker.checkEq("property description", p.getShortDescription(), "BASE");

        Checker.checkEq("isBound",  p.isBound(),  true);
        Checker.checkEq("isExpert", p.isExpert(), true);
        Checker.checkEq("isHidden", p.isHidden(), true);
        Checker.checkEq("isPreferred", p.isPreferred(), true);
        Checker.checkEq("required", p.getValue("required"), true);
        Checker.checkEq("visualUpdate", p.getValue("visualUpdate"), true);

        Checker.checkEnumEq("enumerationValues", p.getValue("enumerationValues"),
            new Object[]{"TOP", 1, "javax.swing.SwingConstants.TOP"});
    }
 
Example 26
Project: lams   File: BasicPropertyAccessor.java   View source code 6 votes vote down vote up
private static Method setterMethod(Class theClass, String propertyName) {
	BasicGetter getter = getGetterOrNull(theClass, propertyName);
	Class returnType = (getter==null) ? null : getter.getReturnType();

	Method[] methods = theClass.getDeclaredMethods();
	Method potentialSetter = null;
	for ( Method method : methods ) {
		final String methodName = method.getName();

		if ( method.getParameterTypes().length == 1 && methodName.startsWith( "set" ) ) {
			String testStdMethod = Introspector.decapitalize( methodName.substring( 3 ) );
			String testOldMethod = methodName.substring( 3 );
			if ( testStdMethod.equals( propertyName ) || testOldMethod.equals( propertyName ) ) {
				potentialSetter = method;
				if ( returnType == null || method.getParameterTypes()[0].equals( returnType ) ) {
					return potentialSetter;
				}
			}
		}
	}
	return potentialSetter;
}
 
Example 27
Project: bird-java   File: InstanceHelper.java   View source code 6 votes vote down vote up
public static Map<String, Object> transBean2Map(Object obj) {
    Map<String, Object> map = newHashMap();
    if (obj == null) {
        return map;
    }
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        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) {
        System.out.println("transBean2Map Error " + e);
    }
    return map;
}
 
Example 28
Project: gate-core   File: SerialDatastoreViewer.java   View source code 6 votes vote down vote up
/**
 * Sets the value for a specified parameter.
 * 
 * @param paramaterName the name for the parameteer
 * @param parameterValue the value the parameter will receive
 */
@Override
public void setParameterValue(String paramaterName, Object parameterValue)
        throws ResourceInstantiationException {
  // get the beaninfo for the resource bean, excluding data about
  // Object
  BeanInfo resBeanInf = null;
  try {
    resBeanInf = Introspector.getBeanInfo(this.getClass(), Object.class);
  }
  catch(Exception e) {
    throw new ResourceInstantiationException(
            "Couldn't get bean info for resource "
                    + this.getClass().getName() + Strings.getNl()
                    + "Introspector exception was: " + e);
  }
  AbstractResource.setParameterValue(this, resBeanInf, paramaterName,
          parameterValue);
}
 
Example 29
Project: lams   File: Cloneable.java   View source code 6 votes vote down vote up
private void checkListeners() {
	BeanInfo beanInfo = null;
	try {
		beanInfo = Introspector.getBeanInfo( getClass(), Object.class );
		internalCheckListeners( beanInfo );
	}
	catch( IntrospectionException t ) {
		throw new HibernateException( "Unable to validate listener config", t );
	}
	finally {
		if ( beanInfo != null ) {
			// release the jdk internal caches everytime to ensure this
			// plays nicely with destroyable class-loaders
			Introspector.flushFromCaches( getClass() );
		}
	}
}
 
Example 30
Project: sun-members   File: CommonUtil.java   View source code 6 votes vote down vote up
/**
 * map转换为bean
 *
 * @param entityClass
 * @param map
 * @return
 * @throws Exception
 */
public static <T> T map2Bean(Class<T> entityClass, Map<String, Object> map) throws Exception {
    BeanInfo beanInfo = Introspector.getBeanInfo(entityClass); // 获取类属性
    T obj = entityClass.newInstance(); // 创建 JavaBean 对象
    // 给 JavaBean 对象的属性赋值
    PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    if (null != propertyDescriptors) {
        for (int i = 0; i < propertyDescriptors.length; i++) {
            PropertyDescriptor descriptor = propertyDescriptors[i];
            String propertyName = descriptor.getName();
            if (map.containsKey(propertyName)) {//设置属性值
                try {
                    descriptor.getWriteMethod().invoke(obj, map.get(propertyName));
                } catch (Exception e) {
                    throw e;
                }
            }
        }
    }
    return obj;
}
 
Example 31
Project: lams   File: QuartzSchedulerMBeanImpl.java   View source code 6 votes vote down vote up
private static Method findMethod(Class<?> targetType, String methodName,
        Class<?>[] argTypes) throws IntrospectionException {
    BeanInfo beanInfo = Introspector.getBeanInfo(targetType);
    if (beanInfo != null) {
        for(MethodDescriptor methodDesc: beanInfo.getMethodDescriptors()) {
            Method method = methodDesc.getMethod();
            Class<?>[] parameterTypes = method.getParameterTypes();
            if (methodName.equals(method.getName()) && argTypes.length == parameterTypes.length) {
                boolean matchedArgTypes = true;
                for (int i = 0; i < argTypes.length; i++) { 
                    if (getWrapperIfPrimitive(argTypes[i]) != parameterTypes[i]) {
                        matchedArgTypes = false;
                        break;
                    }
                }
                if (matchedArgTypes) {
                    return method;
                }
            }
        }
    }
    return null;
}
 
Example 32
Project: zooadmin   File: BeanMapUtil.java   View source code 6 votes vote down vote up
public static Object convertMap2Bean(Class type, Map map)
		throws IntrospectionException, IllegalAccessException,
		InstantiationException, InvocationTargetException {
	BeanInfo beanInfo = Introspector.getBeanInfo(type);
	Object obj = type.newInstance();
	PropertyDescriptor[] propertyDescriptors = beanInfo
			.getPropertyDescriptors();
	for (PropertyDescriptor pro : propertyDescriptors) {
		String propertyName = pro.getName();
		if (pro.getPropertyType().getName().equals("java.lang.Class")) {
			continue;
		}
		if (map.containsKey(propertyName)) {
			Object value = map.get(propertyName);
			Method setter = pro.getWriteMethod();
			setter.invoke(obj, value);
		}
	}
	return obj;
}
 
Example 33
Project: openjdk-jdk10   File: Test6447751.java   View source code 6 votes vote down vote up
private static void test(Class<?> type, Class<?> expected) {
    Class<?> actual;
    try {
        actual = Introspector.getBeanInfo(type).getBeanDescriptor().getCustomizerClass();
    }
    catch (IntrospectionException exception) {
        throw new Error("unexpected error", exception);
    }
    if (actual != expected) {
        StringBuilder sb = new StringBuilder();
        sb.append("bean ").append(type).append(": ");
        if (expected != null) {
            sb.append("expected ").append(expected);
            if (actual != null) {
                sb.append(", but ");
            }
        }
        if (actual != null) {
            sb.append("found ").append(actual);
        }
        throw new Error(sb.toString());
    }
}
 
Example 34
Project: GitHub   File: BeanFriendlyTest.java   View source code 5 votes vote down vote up
@Test
public void modifiableAsJavaBean() throws Exception {
  ImmutableSet<String> rwProperties =
      ImmutableSet.of("primary", "id", "description", "names", "options", "extra");

  FluentIterable<PropertyDescriptor> propertyDescriptors =
      FluentIterable.of(
          Introspector.getBeanInfo(ModifiableBeanFriendly.class)
              .getPropertyDescriptors());

  check(propertyDescriptors.transform(p -> p.getName()).toSet().containsAll(rwProperties));

  for (PropertyDescriptor pd : propertyDescriptors) {
    check(pd.getReadMethod()).notNull();
    if (rwProperties.contains(pd.getName())) {
      check(pd.getWriteMethod()).notNull();
    }
  }

  ModifiableBeanFriendly bean = new ModifiableBeanFriendly();
  bean.setPrimary(true);
  bean.setDescription("description");
  bean.setId(1000);
  bean.setNames(ImmutableList.of("name"));
  bean.addNames("name2");
  bean.putOptions("foo", "bar");

  // This bean can become immutable.
  BeanFriendly immutableBean = bean.toImmutable();
  check(immutableBean.isPrimary());
  check(immutableBean.getDescription()).is("description");
  check(immutableBean.getId()).is(1000);
  check(immutableBean.getNames()).isOf("name", "name2");
  check(immutableBean.getOptions()).is(ImmutableMap.of("foo", "bar"));
}
 
Example 35
Project: redant   File: BeanHolder.java   View source code 5 votes vote down vote up
/**
 * 处理在set方法加入的注解
 * @param bean 处理的bean
 */
private void propertyAnnotation(Object bean){
    try {
        //获取其属性的描述
        PropertyDescriptor[] descriptors = Introspector.getBeanInfo(bean.getClass()).getPropertyDescriptors();
        for(PropertyDescriptor descriptor : descriptors){
            //获取所有set方法
            Method setter = descriptor.getWriteMethod();
            //判断set方法是否定义了注解
            if(setter!=null && setter.isAnnotationPresent(Autowired.class)){
                //获取当前注解,并判断name属性是否为空
                Autowired resource = setter.getAnnotation(Autowired.class);
                String name;
                Object value = null;
                if(StrUtil.isNotBlank(resource.name())){
                    //获取注解的name属性的内容
                    name = resource.name();
                    value = beanHolderMap.get(name);
                }else{ //如果当前注解没有指定name属性,则根据类型进行匹配
                    for(Map.Entry<String,Object>  entry : beanHolderMap.entrySet()){
                        //判断当前属性所属的类型是否在beanHolderMap中存在
                        if(descriptor.getPropertyType().isAssignableFrom(entry.getValue().getClass())){
                            //获取类型匹配的实例对象
                            value = entry.getValue();
                            break;
                        }
                    }
                }
                //允许访问private方法
                setter.setAccessible(true);
                //把引用对象注入属性
                setter.invoke(bean, value);
            }
        }
    } catch (Exception e) {
        logger.info("propertyAnnotation error,cause:",e);
    }
}
 
Example 36
Project: jdk8u-jdk   File: Test4168475.java   View source code 5 votes vote down vote up
public static void main(String[] args) throws IntrospectionException {
    Introspector.setBeanInfoSearchPath(PATH);
    BeanInfo info = Introspector.getBeanInfo(Component.class);
    PropertyDescriptor[] pds = info.getPropertyDescriptors();

    // The custom ComponentBeanInfo we deliver
    // only provides a single property.

    if (pds.length != 1) {
        throw new Error("wrong number of properties");
    }
    if (!pds[0].getName().equals("name")) {
        throw new Error("unexpected property name");
    }
}
 
Example 37
Project: openjdk-jdk10   File: UnloadClassBeanInfo.java   View source code 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
    Class cl = getStub();
    System.out.println("cl.getClassLoader() = " + cl.getClassLoader());
    final BeanInfo beanInfo = Introspector.getBeanInfo(cl, Object.class);
    MethodDescriptor[] mds = beanInfo.getMethodDescriptors();
    System.out.println("mds = " + Arrays.toString(mds));
    loader.close();
    loader=null;
    cl=null;
    Util.generateOOME();
    mds = beanInfo.getMethodDescriptors();
    System.out.println("mds = " + Arrays.toString(mds));
}
 
Example 38
Project: incubator-netbeans   File: JarDataLoaderBeanInfo.java   View source code 5 votes vote down vote up
public BeanInfo[] getAdditionalBeanInfo() {
    try {
        return new BeanInfo[] {Introspector.getBeanInfo(UniFileLoader.class)};
    } catch (IntrospectionException ie) {
        throw new AssertionError(ie);
    }
}
 
Example 39
Project: incubator-netbeans   File: FormJavaSource.java   View source code 5 votes vote down vote up
public static String extractPropertyName(String methodName) {
for (int i = 0; i < PROPERTY_PREFIXES.length; i++) {
    if(methodName.startsWith(PROPERTY_PREFIXES[i]) && 
       methodName.length() > PROPERTY_PREFIXES[i].length()) 
    {		    
	return Introspector.decapitalize(methodName.substring(PROPERTY_PREFIXES[i].length()));		     			
    }	
}
return "";  // NOI18N	
   }
 
Example 40
Project: incubator-netbeans   File: FormDataLoaderBeanInfo.java   View source code 5 votes vote down vote up
@Override
public BeanInfo[] getAdditionalBeanInfo() {
    try {
        return new BeanInfo[] { Introspector.getBeanInfo(MultiFileLoader.class) };
    } catch (IntrospectionException ie) {
        org.openide.ErrorManager.getDefault().notify(ie);
        return null;
    }
}