Java Code Examples for java.beans.IntrospectionException

The following examples show how to use java.beans.IntrospectionException. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
private static void test(StringBuilder sb) throws IntrospectionException {
    long time = 0L;
    if (sb != null) {
        sb.append("Time\t#Props\t#Events\t#Methods\tClass\n");
        sb.append("----------------------------------------");
        time = -System.currentTimeMillis();
    }
    for (Class type : TYPES) {
        test(sb, type);
    }
    if (sb != null) {
        time += System.currentTimeMillis();
        sb.append("\nTime: ").append(time).append(" ms\n");
        System.out.println(sb);
        sb.setLength(0);
    }
}
 
Example 2
Source Project: openjdk-8-source   Source File: Test6447751.java    License: GNU General Public License v2.0 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 3
Source Project: j2objc   Source File: EventSetDescriptorTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testEventSetDescriptorClassStringClassStringArrayStringString_sourceClassNull()
        throws IntrospectionException {
    Class<?> sourceClass = null;
    String eventSetName = "MockPropertyChange";
    Class<?> listenerType = MockPropertyChangeListener.class;
    String[] listenerMethodNames = { "mockPropertyChange",
            "mockPropertyChange2", };
    String addMethod = "addMockPropertyChangeListener";
    String removeMethod = "removeMockPropertyChangeListener";

    try {
        new EventSetDescriptor(sourceClass, eventSetName, listenerType,
                listenerMethodNames, addMethod, removeMethod);
        fail("Should throw NullPointerException.");
    } catch (NullPointerException e) {
    }
}
 
Example 4
Source Project: gemfirexd-oss   Source File: MBeanProxyInvocationHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param member
 *          member to which this MBean belongs
 * @param monitoringRegion
 *          corresponding MonitoringRegion
 * @param objectName
 *          ObjectName of the MBean
 * @param interfaceClass
 *          on which interface the proxy to be exposed
 * @return Object
 * @throws ClassNotFoundException
 * @throws IntrospectionException
 */
public static Object newProxyInstance(DistributedMember member,
    Region<String, Object> monitoringRegion, ObjectName objectName,
    Class interfaceClass) throws ClassNotFoundException,
    IntrospectionException {
  boolean isMXBean = JMX.isMXBeanInterface(interfaceClass);
  boolean notificationBroadcaster = ((FederationComponent) monitoringRegion
      .get(objectName.toString())).isNotificationEmitter();

  InvocationHandler handler = new MBeanProxyInvocationHandler(member,
      objectName, monitoringRegion, isMXBean);

  Class[] interfaces;

  if (notificationBroadcaster) {
    interfaces = new Class[] { interfaceClass, ProxyInterface.class,
        NotificationBroadCasterProxy.class };
  } else {
    interfaces = new Class[] { interfaceClass, ProxyInterface.class };
  }

  Object proxy = Proxy.newProxyInstance(MBeanProxyInvocationHandler.class
      .getClassLoader(), interfaces, handler);

  return interfaceClass.cast(proxy);
}
 
Example 5
Source Project: jdk8u-jdk   Source File: TestIntrospector.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static void test(StringBuilder sb) throws IntrospectionException {
    long time = 0L;
    if (sb != null) {
        sb.append("Time\t#Props\t#Events\t#Methods\tClass\n");
        sb.append("----------------------------------------");
        time = -System.currentTimeMillis();
    }
    for (Class type : TYPES) {
        test(sb, type);
    }
    if (sb != null) {
        time += System.currentTimeMillis();
        sb.append("\nTime: ").append(time).append(" ms\n");
        System.out.println(sb);
        sb.setLength(0);
    }
}
 
Example 6
Source Project: j2objc   Source File: IndexedPropertyDescriptorTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testIndexedPropertyDescriptorStringMethodMethodMethodMethod_RWNull()
        throws SecurityException, NoSuchMethodException,
        IntrospectionException {
    String propertyName = "PropertyFour";
    Class<MockJavaBean> beanClass = MockJavaBean.class;

    Method indexedReadMethod = beanClass.getMethod("get" + propertyName,
            new Class[] { Integer.TYPE });
    Method indexedWriteMethod = beanClass.getMethod("set" + propertyName,
            new Class[] { Integer.TYPE, String.class });

    IndexedPropertyDescriptor ipd = new IndexedPropertyDescriptor(
            propertyName, null, null, indexedReadMethod, indexedWriteMethod);

    assertNull(ipd.getPropertyType());
    assertEquals(String.class, ipd.getIndexedPropertyType());

}
 
Example 7
Source Project: java-technology-stack   Source File: ExtendedBeanInfoTests.java    License: MIT License 6 votes vote down vote up
@Test
public void nonStandardReadMethodAndStandardWriteMethod() throws IntrospectionException {
	@SuppressWarnings("unused") class C {
		public void getFoo() { }
		public void setFoo(String foo) { }
	}

	BeanInfo bi = Introspector.getBeanInfo(C.class);
	BeanInfo ebi = new ExtendedBeanInfo(bi);

	assertThat(hasReadMethodForProperty(bi, "foo"), is(false));
	assertThat(hasWriteMethodForProperty(bi, "foo"), is(true));

	assertThat(hasReadMethodForProperty(ebi, "foo"), is(false));
	assertThat(hasWriteMethodForProperty(ebi, "foo"), is(true));
}
 
Example 8
Source Project: java-technology-stack   Source File: CachedIntrospectionResults.java    License: MIT License 6 votes vote down vote up
private void introspectInterfaces(Class<?> beanClass, Class<?> currClass) throws IntrospectionException {
	for (Class<?> ifc : currClass.getInterfaces()) {
		if (!ClassUtils.isJavaLanguageInterface(ifc)) {
			for (PropertyDescriptor pd : getBeanInfo(ifc).getPropertyDescriptors()) {
				PropertyDescriptor existingPd = this.propertyDescriptorCache.get(pd.getName());
				if (existingPd == null ||
						(existingPd.getReadMethod() == null && pd.getReadMethod() != null)) {
					// GenericTypeAwarePropertyDescriptor leniently resolves a set* write method
					// against a declared read method, so we prefer read method descriptors here.
					pd = buildGenericTypeAwarePropertyDescriptor(beanClass, pd);
					this.propertyDescriptorCache.put(pd.getName(), pd);
				}
			}
			introspectInterfaces(ifc, ifc);
		}
	}
}
 
Example 9
Source Project: spring-analysis-note   Source File: ExtendedBeanInfoTests.java    License: MIT License 6 votes vote down vote up
@Test
public void indexedWriteMethodOnly() throws IntrospectionException {
	@SuppressWarnings("unused")
	class C {
		// indexed write method
		public void setFoos(int i, String foo) { }
	}

	BeanInfo bi = Introspector.getBeanInfo(C.class);
	BeanInfo ebi = new ExtendedBeanInfo(Introspector.getBeanInfo(C.class));

	assertThat(hasWriteMethodForProperty(bi, "foos"), is(false));
	assertThat(hasIndexedWriteMethodForProperty(bi, "foos"), is(true));

	assertThat(hasWriteMethodForProperty(ebi, "foos"), is(false));
	assertThat(hasIndexedWriteMethodForProperty(ebi, "foos"), is(true));
}
 
Example 10
Source Project: Openfire   Source File: JiveBeanInfo.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public PropertyDescriptor[] getPropertyDescriptors() {
    Class beanClass = getBeanClass();
    String[] properties = getPropertyNames();

    PropertyDescriptor[] descriptors = new PropertyDescriptor[properties.length];
    try {
        // For each property, create a property descriptor and set the
        // name and description using the localized data.
        for (int i = 0; i < descriptors.length; i++) {
            PropertyDescriptor newDescriptor =
                    new PropertyDescriptor(properties[i], beanClass);
            if (bundle != null) {
                newDescriptor.setDisplayName(bundle.getString(properties[i] + ".displayName"));
                newDescriptor.setShortDescription(bundle.getString(properties[i] + ".shortDescription"));
            }
            descriptors[i] = newDescriptor;
        }
        return descriptors;
    }
    catch (IntrospectionException ie) {
        Log.error(ie.getMessage(), ie);
        throw new Error(ie.toString());
    }
}
 
Example 11
Source Project: netbeans   Source File: CatalogNode.java    License: Apache License 2.0 6 votes vote down vote up
/** Creates new CatalogNode */
public CatalogNode(CatalogReader catalog) throws IntrospectionException {        
    super(catalog, new CatalogChildren(catalog));
    this.catalog=catalog;
    getCookieSet().add(this);
    
    if (catalog instanceof CatalogDescriptorBase) {
        
        // set node properties acording to descriptor
        
        CatalogDescriptorBase desc = (CatalogDescriptorBase) catalog;            
        setSynchronizeName(false);
        setName(desc.getDisplayName());
        String bundleString = catalog instanceof CatalogWriter ?"LBL_catalogReadWrite":"LBL_catalogReadOnly"; //NOI18N
        setDisplayName(NbBundle.getMessage(CatalogNode.class, bundleString, desc.getDisplayName()));
        setShortDescription(desc.getShortDescription());
        fireIconChange();  

        // listen on it
        
        desc.addPropertyChangeListener(WeakListeners.propertyChange(this, desc));
    }
}
 
Example 12
Source Project: DataFrame   Source File: FieldColumn.java    License: MIT License 6 votes vote down vote up
/**
 * Converts the value object and inserts it in the field of an object.
 * The field name is defined as the field name in this object
 *
 * @param value  value that is converted and inserted
 * @param object object that gets the value inserted
 */
public void set(Object value, Object object) {
    Object convertedVal;
    if (field.getType().isInstance(value)) {
        convertedVal = value;
    } else {
        convertedVal = ParserUtil.parseOrNull(field.getType(), value.toString());
    }
    try {
        if (Modifier.isPublic(field.getModifiers())) {
            field.set(object, convertedVal);
        } else {
            PropertyDescriptor objPropertyDescriptor = new PropertyDescriptor(field.getName(), object.getClass());
            objPropertyDescriptor.getWriteMethod().invoke(object, convertedVal);
        }
    } catch (IllegalAccessException | InvocationTargetException | IntrospectionException e) {
        e.printStackTrace();
    }
}
 
Example 13
Source Project: APICloud-Studio   Source File: BundleCacher.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
protected Set<Property> getProperties(Class<? extends Object> type) throws IntrospectionException
{
	if (type.equals(Ruby.class) || type.equals(KCode.class) || type.equals(RubyProc.class))
	{
		return Collections.emptySet();
	}
	Set<Property> set = super.getProperties(type);
	if (CommandElement.class.isAssignableFrom(type) || type.equals(EnvironmentElement.class))
	{
		// drop runtime, invoke, and invoke block properties
		Set<Property> toRemove = new HashSet<Property>();
		for (Property prop : set)
		{
			if ("invokeBlock".equals(prop.getName()) || "runtime".equals(prop.getName()) //$NON-NLS-1$ //$NON-NLS-2$
					|| "invoke".equals(prop.getName())) //$NON-NLS-1$
			{
				toRemove.add(prop);
			}
		}

		set.removeAll(toRemove);
	}
	return set;
}
 
Example 14
/** Constructor for the JOutlookBarBeanInfo object */
public JOutlookBarBeanInfo() throws java.beans.IntrospectionException
{
	// setup bean descriptor in constructor. 
    bd.setName("JOutlookBar");

    bd.setShortDescription("JOutlookBar brings the famous Outlook component to Swing");

    BeanInfo info = Introspector.getBeanInfo(getBeanDescriptor().getBeanClass().getSuperclass());
    String order = info.getBeanDescriptor().getValue("propertyorder") == null ? "" : (String) info.getBeanDescriptor().getValue("propertyorder");
    PropertyDescriptor[] pd = getPropertyDescriptors();
    for (int i = 0; i != pd.length; i++)
    {
       if (order.indexOf(pd[i].getName()) == -1)
       {
          order = order + (order.length() == 0 ? "" : ":") + pd[i].getName();
       }
    }
    getBeanDescriptor().setValue("propertyorder", order);
}
 
Example 15
Source Project: netbeans   Source File: HelpCtx.java    License: Apache License 2.0 6 votes vote down vote up
/** Finds help context for a generic object. Right now checks
 * for HelpCtx.Provider and handles java.awt.Component in a
 * special way compatible with JavaHelp.
 * Also {@link BeanDescriptor}'s are checked for a string-valued attribute
 * <code>helpID</code>, as per the JavaHelp specification (but no help sets
 * will be loaded).
 *
 * @param instance to search help for
 * @return the help for the object or <code>HelpCtx.DEFAULT_HELP</code> if HelpCtx cannot be found
 *
 * @since 4.3
 */
public static HelpCtx findHelp(Object instance) {
    if (instance instanceof java.awt.Component) {
        return findHelp((java.awt.Component) instance);
    }

    if (instance instanceof HelpCtx.Provider) {
        return ((HelpCtx.Provider) instance).getHelpCtx();
    }

    try {
        BeanDescriptor d = Introspector.getBeanInfo(instance.getClass()).getBeanDescriptor();
        String v = (String) d.getValue("helpID"); // NOI18N

        if (v != null) {
            return new HelpCtx(v);
        }
    } catch (IntrospectionException e) {
        err.log(Level.FINE, "findHelp on {0}: {1}", new Object[]{instance, e});
    }

    return HelpCtx.DEFAULT_HELP;
}
 
Example 16
Source Project: boon   Source File: Annotations.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Find annotation given a particular property name and clazz. This figures
 * out the writeMethod for the property, and uses the write method
 * to look up the annotation.
 *
 * @param clazz        The class that holds the property.
 * @param propertyName The name of the property.
 * @return
 * @throws java.beans.IntrospectionException
 *
 */
private static Annotation[] findPropertyAnnotations( Class<?> clazz, String propertyName, boolean useRead )
        throws IntrospectionException {

    PropertyDescriptor propertyDescriptor = getPropertyDescriptor( clazz, propertyName );
    if ( propertyDescriptor == null ) {
        return new Annotation[]{ };
    }
    Method accessMethod = null;

    if ( useRead ) {
        accessMethod = propertyDescriptor.getReadMethod();
    } else {
        accessMethod = propertyDescriptor.getWriteMethod();
    }

    if ( accessMethod != null ) {
        Annotation[] annotations = accessMethod.getAnnotations();
        return annotations;
    } else {
        return new Annotation[]{ };
    }
}
 
Example 17
Source Project: genericdao   Source File: FieldHelper.java    License: Artistic License 2.0 6 votes vote down vote up
/**
 * 通过方法获取属性
 * @param entityClass
 * @return
 */
public List<EntityField> getProperties(Class<?> entityClass) {
    List<EntityField> entityFields = new ArrayList<EntityField>();
    BeanInfo beanInfo = null;
    try {
        beanInfo = Introspector.getBeanInfo(entityClass);
    } catch (IntrospectionException e) {
        throw new RuntimeException(e);
    }
    PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
    for (PropertyDescriptor desc : descriptors) {
        if (!desc.getName().equals("class")) {
            entityFields.add(new EntityField(desc));
        }
    }
    return entityFields;
}
 
Example 18
Source Project: jdk8u-dev-jdk   Source File: Test4634390.java    License: 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 19
Source Project: packagedrone   Source File: Generator.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Constructor.
 *
 * @param n The custom tag whose tag handler class is to be
 * introspected
 * @param tagHandlerClass Tag handler class
 * @param err Error dispatcher
 */
TagHandlerInfo(Node n, Class tagHandlerClass, ErrorDispatcher err)
    throws JasperException {
    this.tagHandlerClass = tagHandlerClass;
    this.methodMaps = new HashMap<String, Method>();
    this.propertyEditorMaps = new HashMap<String, Class<?>>();

    try {
        BeanInfo tagClassInfo =
            Introspector.getBeanInfo(tagHandlerClass);
        PropertyDescriptor[] pd = tagClassInfo.getPropertyDescriptors();
        for (int i = 0; i < pd.length; i++) {
            /*
             * FIXME: should probably be checking for things like
             *        pageContext, bodyContent, and parent here -akv
             */
            if (pd[i].getWriteMethod() != null) {
                methodMaps.put(pd[i].getName(), pd[i].getWriteMethod());
            }
            if (pd[i].getPropertyEditorClass() != null)
                propertyEditorMaps.put(
                    pd[i].getName(),
                    pd[i].getPropertyEditorClass());
        }
    } catch (IntrospectionException ie) {
        err.jspError(
            n,
            "jsp.error.introspect.taghandler",
            tagHandlerClass.getName(),
            ie);
    }
}
 
Example 20
Source Project: phone   Source File: ExcelExportSuper.java    License: Apache License 2.0 5 votes vote down vote up
Object getValueByKey(T t,String key) throws NoSuchFieldException, SecurityException, IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
Object formatValue = formatValue(t, key);
if (formatValue!=null) {
	return formatValue;
}
if(t instanceof Map){
	@SuppressWarnings("rawtypes")
	Object returnObject = ((Map) t).get(key);
  		return returnObject;
  	}else{
  		PropertyDescriptor pd = ReflectionUtil.getPropertyDescriptor(key, t);
  		Method rm = pd.getReadMethod();
  		return rm.invoke(t);
  	}
  }
 
Example 21
Source Project: spring4-understanding   Source File: ExtendedBeanInfo.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Class<?> getIndexedPropertyType() {
	if (this.indexedPropertyType == null) {
		try {
			this.indexedPropertyType = PropertyDescriptorUtils.findIndexedPropertyType(
					getName(), getPropertyType(), this.indexedReadMethod, this.indexedWriteMethod);
		}
		catch (IntrospectionException ex) {
			// Ignore, as does IndexedPropertyDescriptor#getIndexedPropertyType
		}
	}
	return this.indexedPropertyType;
}
 
Example 22
/**
 * Tests that a defensive copy is created from the collection with properties to be
 * removed.
 */
public void testPropertyNamesDefensiveCopy() throws IntrospectionException {
    final Collection<String> properties = new HashSet<>();
    properties.add("prop1");
    final SuppressPropertiesBeanIntrospector introspector = new SuppressPropertiesBeanIntrospector(
            properties);
    properties.add("prop2");
    final IntrospectionContextTestImpl context = new IntrospectionContextTestImpl();

    introspector.introspect(context);
    assertEquals("Wrong number of removed properties", 1, context
            .getRemovedProperties().size());
    assertTrue("Wrong removed property",
            context.getRemovedProperties().contains("prop1"));
}
 
Example 23
@Override
public PropertyDescriptor[] getPropertyDescriptors() {
    try {
        return new PropertyDescriptor[] {
                new PropertyDescriptor(PROPERTY, Enumeration.class, GETTER, SETTER)
        };
    }
    catch (IntrospectionException exception) {
        throw new Error("unexpected exception", exception);
    }
}
 
Example 24
Source Project: openjdk-8-source   Source File: Test6277246.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws IntrospectionException {
    Class type = BASE64Encoder.class;
    System.setSecurityManager(new SecurityManager());
    BeanInfo info = Introspector.getBeanInfo(type);
    for (MethodDescriptor md : info.getMethodDescriptors()) {
        Method method = md.getMethod();
        System.out.println(method);

        String name = method.getDeclaringClass().getName();
        if (name.startsWith("sun.misc.")) {
            throw new Error("found inaccessible method");
        }
    }
}
 
Example 25
public ExtendedPropertyDescriptor(
  String propertyName,
  Method getter,
  Method setter)
  throws IntrospectionException {
  super(propertyName, getter, setter);
}
 
Example 26
public void testIndexedProperties() throws IntrospectionException, BeanException {
  final TestBean testBean = new TestBean();
  testBean.setArrayOnly( new String[1] );
  testBean.setFullyIndexed( new String[1] );
  testBean.setIndexOnly( 0, null );
  final BeanUtility bu = new BeanUtility( testBean );
  validateProperty( bu, "arrayOnly[0]", "Color.red", null );
  validateProperty( bu, "fullyIndexed[0]", "Hello World", null );
  validateProperty( bu, "indexOnly[0]", "Boolean.TRUE", null );
}
 
Example 27
Source Project: snake-yaml   Source File: GenericsBugDetector.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Check whether the proper class Nest for Bird's property 'home' is
 * recognized.
 */
public static boolean isProperIntrospection() throws IntrospectionException {
    for (PropertyDescriptor property : Introspector.getBeanInfo(Bird.class)
            .getPropertyDescriptors()) {
        if (property.getName().equals("home")) {
            return property.getPropertyType() == Nest.class;
        }
    }
    throw new RuntimeException("Bird must contain 'home' property.");
}
 
Example 28
Source Project: openjdk-8-source   Source File: BeanUtils.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns an array of property descriptors for specified class.
 *
 * @param type  the class to introspect
 * @return an array of property descriptors
 */
public static PropertyDescriptor[] getPropertyDescriptors(Class type) {
    try {
        return Introspector.getBeanInfo(type).getPropertyDescriptors();
    } catch (IntrospectionException exception) {
        throw new Error("unexpected exception", exception);
    }
}
 
Example 29
Source Project: spring-analysis-note   Source File: CachedIntrospectionResults.java    License: MIT License 5 votes vote down vote up
private PropertyDescriptor buildGenericTypeAwarePropertyDescriptor(Class<?> beanClass, PropertyDescriptor pd) {
	try {
		return new GenericTypeAwarePropertyDescriptor(beanClass, pd.getName(), pd.getReadMethod(),
				pd.getWriteMethod(), pd.getPropertyEditorClass());
	}
	catch (IntrospectionException ex) {
		throw new FatalBeanException("Failed to re-introspect class [" + beanClass.getName() + "]", ex);
	}
}
 
Example 30
Source Project: j2objc   Source File: PropertyDescriptorTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testEqualsRegression1763() throws IntrospectionException {
    String propertyName = "PropertyOne";
    Class<MockJavaBean> beanClass = MockJavaBean.class;
    PropertyDescriptor pd = new PropertyDescriptor(propertyName, beanClass);

    try {
        pd.equals(propertyName);
    } catch (ClassCastException e) {
        fail("Equals throws ClassCastException");
    }
}