下面列出了怎么用java.beans.BeanInfo的API类实例代码及写法,或者点击链接到github查看源代码。
public void test_MixedBooleanSimpleClass3() throws Exception {
BeanInfo info = Introspector
.getBeanInfo(MixedBooleanSimpleClass3.class);
Method getter = MixedBooleanSimpleClass3.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(getter, ((IndexedPropertyDescriptor) pd)
.getIndexedReadMethod());
assertNull(((IndexedPropertyDescriptor) pd)
.getIndexedWriteMethod());
}
}
}
public static Map<String, String> toStringMap(Object obj) {
Map<String, String> map = null;
if (obj == null) {
return map;
}
map = new HashMap<String, String>();
try {
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
if (!key.equals("class")) {
Method getter = property.getReadMethod();
map.put(key, getter.invoke(obj).toString());
}
}
} catch (Exception e) {
map = null;
}
return map;
}
private void configureMenuItem (JMenuItem item, String containerCtx, String action, ActionProvider provider, Map context) {
// System.err.println("ConfigureMenuItem: " + containerCtx + "/" + action);
item.setName(action);
item.putClientProperty(KEY_ACTION, action);
item.putClientProperty(KEY_CONTAINERCONTEXT, containerCtx);
item.putClientProperty(KEY_CREATOR, this);
item.setText(
provider.getDisplayName(action, containerCtx));
item.setToolTipText(provider.getDescription(action, containerCtx));
int state = context == null ? ActionProvider.STATE_ENABLED | ActionProvider.STATE_VISIBLE :
provider.getState (action, containerCtx, context);
boolean enabled = (state & ActionProvider.STATE_ENABLED) != 0;
item.setEnabled(enabled);
boolean visible = (state & ActionProvider.STATE_VISIBLE) != 0;
//Intentionally use enabled property
item.setVisible(enabled);
item.setMnemonic(provider.getMnemonic(action, containerCtx));
item.setDisplayedMnemonicIndex(provider.getMnemonicIndex(action, containerCtx));
item.setIcon(provider.getIcon(action, containerCtx, BeanInfo.ICON_COLOR_16x16));
}
/** 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);
}
public static Map<String, Object> toMapNotNull(Object obj) {
if (obj == null)
return null;
Map<String, Object> result = new HashMap<>();
BeanInfo beanInfo = getBeanInfo(obj.getClass());
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor pd : pds) {
String name = pd.getName();
if (ignores.contains(name))
continue;
Object value = getValue(obj, pd.getReadMethod());
if (value != null)
result.put(name, value);
}
return result;
}
public void test_MixedSimpleClass19() throws Exception {
BeanInfo info = Introspector.getBeanInfo(MixedSimpleClass19.class);
Method getter = MixedSimpleClass19.class.getDeclaredMethod("getList",
int.class);
Method setter = MixedSimpleClass19.class.getDeclaredMethod("setList",
int.class, Object.class);
for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
if (propertyName.equals(pd.getName())) {
assertTrue(pd instanceof IndexedPropertyDescriptor);
assertNull(pd.getReadMethod());
assertNull(pd.getWriteMethod());
assertEquals(getter, ((IndexedPropertyDescriptor) pd)
.getIndexedReadMethod());
assertEquals(setter, ((IndexedPropertyDescriptor) pd)
.getIndexedWriteMethod());
}
}
}
public void testMockIncompatibleGetterAndIndexedGetterBean() throws Exception {
Class<?> beanClass = MockIncompatibleGetterAndIndexedGetterBean.class;
BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
PropertyDescriptor pd = null;
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
for (int i = 0; i < pds.length; i++) {
pd = pds[i];
if (pd.getName().equals("data")) {
break;
}
}
assertNotNull(pd);
assertTrue(pd instanceof IndexedPropertyDescriptor);
IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor) pd;
assertNull(ipd.getReadMethod());
assertNull(ipd.getWriteMethod());
Method indexedReadMethod = beanClass.getMethod("getData",
new Class[] { int.class });
Method indexedWriteMethod = beanClass.getMethod("setData", new Class[] {
int.class, int.class });
assertEquals(indexedReadMethod, ipd.getIndexedReadMethod());
assertEquals(indexedWriteMethod, ipd.getIndexedWriteMethod());
}
private RootClassInfo(String className, List<String> warnings) {
super();
this.className = className;
this.warnings = warnings;
if (className == null) {
return;
}
try {
Class<?> clazz = ObjectFactory.externalClassForName(className);
BeanInfo bi = Introspector.getBeanInfo(clazz);
propertyDescriptors = bi.getPropertyDescriptors();
} catch (Exception e) {
propertyDescriptors = null;
warnings.add(getString("Warning.20", className)); //$NON-NLS-1$
}
}
@Test
public void propertyCountsWithNonStandardWriteMethod() throws IntrospectionException {
class ExtendedTestBean extends TestBean {
@SuppressWarnings("unused")
public ExtendedTestBean setFoo(String s) { return this; }
}
BeanInfo bi = Introspector.getBeanInfo(ExtendedTestBean.class);
BeanInfo ebi = new ExtendedBeanInfo(bi);
boolean found = false;
for (PropertyDescriptor pd : ebi.getPropertyDescriptors()) {
if (pd.getName().equals("foo")) {
found = true;
}
}
assertThat(found, is(true));
assertThat(ebi.getPropertyDescriptors().length, equalTo(bi.getPropertyDescriptors().length+1));
}
/**
* 通过方法获取属性
*
* @param entityClass
* @return
*/
@Override
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 MapperException(e);
}
PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor desc : descriptors) {
if (!"class".equals(desc.getName())) {
entityFields.add(new EntityField(null, desc));
}
}
return entityFields;
}
@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));
}
private void createFields ()
{
try
{
final BeanInfo bi = Introspector.getBeanInfo ( this.objectClass );
for ( final PropertyDescriptor pd : bi.getPropertyDescriptors () )
{
if ( pd.getReadMethod () != null )
{
createDataItem ( pd );
}
}
}
catch ( final Exception e )
{
logger.warn ( "Failed to create fields", e );
}
}
/**
* Test access to the properties of an object through its accessors.
*
* @param obj the object to test
* @throws Exception any exception
*/
public static void assertNoExceptionsOnGetters(final Object obj) throws Exception {
final Class<?> clazz = obj.getClass();
final BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (final PropertyDescriptor propertyDescriptor : propertyDescriptors) {
final Method readMethod = propertyDescriptor.getReadMethod();
if (readMethod != null) {
try {
readMethod.invoke(obj, new Object[] {});
} catch (final InvocationTargetException e) {
final StringBuffer msg = new StringBuffer();
msg.append("Failure: " + propertyDescriptor.getName());
msg.append(" Exception: " + e.getCause().getClass());
msg.append(" Msg: " + e.getCause().getMessage());
throw new AssertionFailedError(msg.toString());
}
}
}
}
@SuppressWarnings("rawtypes")
public BeanInfo[] getAdditionalBeanInfo()
{//GEN-FIRST:Superclass
Class superclass = ProcessVar.class.getSuperclass();
BeanInfo sbi = null;
try
{
sbi = Introspector.getBeanInfo(superclass);//GEN-HEADEREND:Superclass
// Here you can add code for customizing the Superclass BeanInfo.
} catch (IntrospectionException ignored)
{
}
return new BeanInfo[]{sbi};
}
public void test_MixedBooleanSimpleClass31() throws Exception {
BeanInfo info = Introspector
.getBeanInfo(MixedBooleanSimpleClass31.class);
Method indexedGetter = MixedBooleanSimpleClass31.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());
}
}
}
/**
* 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);
}
public DocumentConfiguration(final Class<? extends Document> documentClass, final String namespace) {
if (documentClass == null) {
throw new IllegalArgumentException("Document class for DocumentConfiguration must not be empty");
}
if (namespace == null || namespace.isEmpty()) {
throw new IllegalArgumentException("Namespace for DocumentConfiguration must not be empty");
}
this.documentClass = documentClass;
this.namespace = namespace;
indexDefinitions = new ArrayList<IndexDefinition>();
properties = new HashMap<>();
try {
final BeanInfo beanInfo = Introspector.getBeanInfo(documentClass);
final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (final PropertyDescriptor prop : propertyDescriptors) {
if (!EXCLUDED_PROPERTIES.contains(prop.getName())) {
properties.put(prop.getName(), prop);
}
}
} catch (final IntrospectionException e) {
throw new IllegalStateException(e);
}
}
public void test_MixedSimpleClass61() throws Exception {
BeanInfo beanInfo = Introspector.getBeanInfo(MixedSimpleClass61.class);
Method getter = MixedSimpleClass61.class.getMethod("getList",
new Class<?>[] { int.class });
Method setter = MixedSimpleClass61.class.getMethod("setList",
new Class<?>[] { int.class, boolean.class });
assertEquals(2, beanInfo.getPropertyDescriptors().length);
for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {
if (propertyName.equals(pd.getName())) {
assertNull(pd.getReadMethod());
assertNull(pd.getWriteMethod());
assertTrue(pd instanceof IndexedPropertyDescriptor);
assertEquals(getter,
((IndexedPropertyDescriptor) pd).getIndexedReadMethod());
assertEquals(setter,
((IndexedPropertyDescriptor) pd)
.getIndexedWriteMethod());
}
}
}
/**
* {@link ExtendedBeanInfo} should behave exactly like {@link BeanInfo}
* in strange edge cases.
*/
@Test
public void readMethodReturnsSubtypeOfWriteMethodParameter() throws IntrospectionException {
@SuppressWarnings("unused") class C {
public Integer getFoo() { return null; }
public void setFoo(Number foo) { }
}
BeanInfo bi = Introspector.getBeanInfo(C.class);
BeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasReadMethodForProperty(bi, "foo"), is(true));
assertThat(hasWriteMethodForProperty(bi, "foo"), is(false));
assertThat(hasReadMethodForProperty(ebi, "foo"), is(true));
assertThat(hasWriteMethodForProperty(ebi, "foo"), is(false));
}
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");
}
}
@Override
protected Set<Property> getProperties(Class<?> type) throws IntrospectionException {
Set<Property> set = super.getProperties(type);
Set<Property> filtered = new TreeSet<>();
BeanInfo beanInfo = Introspector.getBeanInfo(type);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
Map<String, PropertyDescriptor> propMap = Arrays.asList(propertyDescriptors).stream().collect(Collectors.toMap(PropertyDescriptor::getName, Function.identity()));
for (Property prop : set) {
PropertyDescriptor pd = propMap.get(prop.getName());
if (pd != null) {
Method readMethod = pd.getReadMethod();
AUTIL.runIfMethodAnnotated(readMethod, () -> filtered.add(prop), false, Transient.class);
}
}
return filtered;
}
public static void copyProperties(Object fromObj, Object toObj) {
Class<?> fromClass = fromObj.getClass();
Class<?> toClass = toObj.getClass();
try {
BeanInfo fromBean = Introspector.getBeanInfo(fromClass);
BeanInfo toBean = Introspector.getBeanInfo(toClass);
PropertyDescriptor[] toPd = toBean.getPropertyDescriptors();
List<PropertyDescriptor> fromPd = Arrays.asList(fromBean.getPropertyDescriptors());
for (PropertyDescriptor propertyDescriptor : toPd) {
propertyDescriptor.getDisplayName();
PropertyDescriptor pd = fromPd.get(fromPd.indexOf(propertyDescriptor));
if (pd.getDisplayName().equals(
propertyDescriptor.getDisplayName()) &&
!pd.getDisplayName().equals("class") &&
propertyDescriptor.getWriteMethod() != null) {
propertyDescriptor.getWriteMethod().invoke(toObj, pd.getReadMethod().invoke(fromObj, null));
}
}
} catch (IntrospectionException | InvocationTargetException | IllegalAccessException | IllegalArgumentException e) {
throw new RuntimeException(e);
}
}
private static Image computeIcon(ServerIcon serverIcon) {
// get the default folder icon
Node folderNode = DataFolder.findFolder(FileUtil.getConfigRoot()).getNodeDelegate();
Image folder;
if (serverIcon == ServerIcon.EJB_OPENED_FOLDER || serverIcon == ServerIcon.WAR_OPENED_FOLDER
|| serverIcon == ServerIcon.EAR_OPENED_FOLDER) {
folder = folderNode.getOpenedIcon(BeanInfo.ICON_COLOR_16x16);
} else {
folder = folderNode.getIcon(BeanInfo.ICON_COLOR_16x16);
}
Image badge;
if (serverIcon == ServerIcon.EJB_FOLDER || serverIcon == ServerIcon.EJB_OPENED_FOLDER) {
badge = ImageUtilities.loadImage("org/netbeans/modules/j2ee/deployment/impl/ui/resources/ejbBadge.png"); // NOI18N
} else if (serverIcon == ServerIcon.WAR_FOLDER || serverIcon == ServerIcon.WAR_OPENED_FOLDER) {
badge = ImageUtilities.loadImage("org/netbeans/modules/j2ee/deployment/impl/ui/resources/warBadge.png"); // NOI18N
} else if (serverIcon == ServerIcon.EAR_FOLDER || serverIcon == ServerIcon.EAR_OPENED_FOLDER) {
badge = ImageUtilities.loadImage("org/netbeans/modules/j2ee/deployment/impl/ui/resources/earBadge.png" ); // NOI18N
} else {
return null;
}
return ImageUtilities.mergeImages(folder, badge, 7, 7);
}
@Test
public void nonPublicStandardReadAndWriteMethods() throws Exception {
@SuppressWarnings("unused") class C {
String getFoo() { return null; }
C setFoo(String foo) { return this; }
}
BeanInfo bi = Introspector.getBeanInfo(C.class);
BeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasReadMethodForProperty(bi, "foo"), is(false));
assertThat(hasWriteMethodForProperty(bi, "foo"), is(false));
assertThat(hasReadMethodForProperty(ebi, "foo"), is(false));
assertThat(hasWriteMethodForProperty(ebi, "foo"), is(false));
}
public static void main(String[] args) throws Exception {
printMemory("Start Memory");
int introspected = 200;
for (int i = 0; i < introspected; i++) {
ClassLoader cl = new SimpleClassLoader();
Class type = cl.loadClass("Bean");
type.newInstance();
// The methods and the bean info should be cached
BeanInfo info = Introspector.getBeanInfo(type);
cl = null;
type = null;
info = null;
System.gc();
}
System.runFinalization();
printMemory("End Memory");
int finalized = SimpleClassLoader.numFinalizers;
System.out.println(introspected + " classes introspected");
System.out.println(finalized + " classes finalized");
// good if at least half of the finalizers are run
if (finalized < (introspected >> 1)) {
throw new Error("ClassLoaders not finalized: " + finalized);
}
}
@Override
public Icon getIcon() {
try {
DataObject d = DataObject.find(file);
Node n = d.getNodeDelegate();
return ImageUtilities.image2Icon(n.getIcon(BeanInfo.ICON_COLOR_16x16));
} catch (DataObjectNotFoundException ex) {
LOG.log(Level.FINE, null, ex);
return null;
}
}
/**
* Bean to map.
*
* @param src the src
* @return the map
* @author: tanyaowu
* @创建时间: 2016年5月10日 下午1:41:53
*/
public static Map<String, Object> beanToMap(Object src)
{
if (src == null)
{
return null;
}
Map<String, Object> map = new HashMap<String, Object>();
try
{
BeanInfo beanInfo = Introspector.getBeanInfo(src.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(src);
map.put(key, value);
}
}
} catch (Exception e)
{
log.error(e.getMessage(), e);
}
return map;
}
public static void main(String[] args) throws Exception {
printMemory("Start Memory");
int introspected = 200;
for (int i = 0; i < introspected; i++) {
ClassLoader cl = new SimpleClassLoader();
Class type = cl.loadClass("Bean");
type.newInstance();
// The methods and the bean info should be cached
BeanInfo info = Introspector.getBeanInfo(type);
cl = null;
type = null;
info = null;
System.gc();
}
System.runFinalization();
printMemory("End Memory");
int finalized = SimpleClassLoader.numFinalizers;
System.out.println(introspected + " classes introspected");
System.out.println(finalized + " classes finalized");
// good if at least half of the finalizers are run
if (finalized < (introspected >> 1)) {
throw new Error("ClassLoaders not finalized: " + finalized);
}
}
/**
* Removes listeners from a resource.
* @param listeners The listeners to be removed from the resource. A
* {@link java.util.Map} that maps from fully qualified class name
* (as a string) to listener (of the type declared by the key).
* @param resource the resource that listeners will be removed from.
*/
public static void removeResourceListeners(Resource resource, Map<String, ? extends Object> listeners)
throws IntrospectionException, InvocationTargetException,
IllegalAccessException, GateException{
// get the beaninfo for the resource bean, excluding data about Object
BeanInfo resBeanInfo = getBeanInfo(resource.getClass());
// get all the events the bean can fire
EventSetDescriptor[] events = resBeanInfo.getEventSetDescriptors();
//remove the listeners
if(events != null) {
EventSetDescriptor event;
for(int i = 0; i < events.length; i++) {
event = events[i];
// did we get such a listener?
Object listener =
listeners.get(event.getListenerType().getName());
if(listener != null) {
Method removeListener = event.getRemoveListenerMethod();
// call the set method with the parameter value
Object[] args = new Object[1];
args[0] = listener;
removeListener.invoke(resource, args);
}
} // for each event
} // if events != null
}
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");
}
}
}