下面列出了怎么用java.beans.IntrospectionException的API类实例代码及写法,或者点击链接到github查看源代码。
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);
}
}
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());
}
}
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) {
}
}
/**
*
* @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);
}
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);
}
}
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());
}
@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));
}
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);
}
}
}
@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));
}
@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());
}
}
/** 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));
}
}
/**
* 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();
}
}
@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;
}
/** 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);
}
/** 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;
}
/**
* 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[]{ };
}
}
/**
* 通过方法获取属性
* @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;
}
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;
}
}
/**
* 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);
}
}
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);
}
}
@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;
}
/**
* 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"));
}
@Override
public PropertyDescriptor[] getPropertyDescriptors() {
try {
return new PropertyDescriptor[] {
new PropertyDescriptor(PROPERTY, Enumeration.class, GETTER, SETTER)
};
}
catch (IntrospectionException exception) {
throw new Error("unexpected exception", exception);
}
}
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");
}
}
}
public ExtendedPropertyDescriptor(
String propertyName,
Method getter,
Method setter)
throws IntrospectionException {
super(propertyName, getter, setter);
}
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 );
}
/**
* 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.");
}
/**
* 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);
}
}
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);
}
}
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");
}
}