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; }
@Override protected void writeResponseResult(HttpServletRequest request, HttpServletResponse response) throws IOException, ServiceException { String className = request.getParameter("className"); String large = request.getParameter("large"); if (className == null || !className.startsWith("com.twinsoft.convertigo.beans")) throw new ServiceException("Must provide className parameter", null); try { BeanInfo bi = CachedIntrospector.getBeanInfo(GenericUtils.<Class<? extends DatabaseObject>>cast(Class.forName(className))); int iconType = large != null && large.equals("true") ? BeanInfo.ICON_COLOR_32x32 : BeanInfo.ICON_COLOR_16x16; IOUtils.copy(bi.getBeanDescriptor().getBeanClass().getResourceAsStream(MySimpleBeanInfo.getIconName(bi, iconType)), response.getOutputStream()); } catch (Exception e) { throw new ServiceException("Icon unreachable", e); } Engine.logAdmin.info("The image has been exported"); }
private static List<ReflectionInfo> fromObject(Integer index, Object obj) throws IntrospectionException { if (obj == null || obj.getClass().getName().startsWith("java.lang") // NOI18N || obj.getClass().getName().startsWith("java.math")) { // NOI18N // Let the default handle this return Collections.singletonList(new ReflectionInfo(index, null)); } else { BeanInfo bi = Introspector.getBeanInfo(obj.getClass(), Object.class); List<ReflectionInfo> result = new ArrayList<>(); for (PropertyDescriptor pd : bi.getPropertyDescriptors()) { result.add(new ReflectionInfo(index, pd.getName())); } if (result.isEmpty()) { return Collections.singletonList(new ReflectionInfo(index, null)); } else { return result; } } }
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() ); } } }
/** * Sets the value for a specified parameter for this resource. * * @param paramaterName the name for the parameter * @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 = getBeanInfo(this.getClass()); } catch(Exception e) { throw new ResourceInstantiationException( "Couldn't get bean info for resource " + this.getClass().getName() + Strings.getNl() + "Introspector exception was: " + e ); } setParameterValue(this, resBeanInf, paramaterName, parameterValue); }
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$ } }
@Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Node node = Visualizer.findNode(value); thumbImage = node.getIcon(BeanInfo.ICON_COLOR_32x32); this.selected = isSelected; label.setOpaque(selected); if (selected) { label.setBackground(UIManager.getColor("List.selectionBackground")); label.setForeground(UIManager.getColor("List.selectionForeground")); } else { label.setBackground(UIManager.getColor("Label.background")); label.setForeground(UIManager.getColor("Label.foreground")); } this.focused = cellHasFocus; this.label.setText(node.getDisplayName()); return this; }
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(), "CHILD"); Checker.checkEq("isBound", p.isBound(), false); Checker.checkEq("isExpert", p.isExpert(), false); Checker.checkEq("isHidden", p.isHidden(), false); Checker.checkEq("isPreferred", p.isPreferred(), false); Checker.checkEq("required", p.getValue("required"), false); Checker.checkEq("visualUpdate", p.getValue("visualUpdate"), false); Checker.checkEnumEq("enumerationValues", p.getValue("enumerationValues"), new Object[]{"BOTTOM", 3, "javax.swing.SwingConstants.BOTTOM"}); }
public static void main(String[] args) throws Exception { BeanInfo i = Introspector.getBeanInfo(C.class, Object.class); Checker.checkEq("description", i.getBeanDescriptor().getShortDescription(), "CHILD"); PropertyDescriptor[] pds = i.getPropertyDescriptors(); Checker.checkEq("number of properties", pds.length, 1); PropertyDescriptor p = pds[0]; Checker.checkEq("property description", p.getShortDescription(), "CHILDPROPERTY"); Checker.checkEq("isBound", p.isBound(), childFlag); Checker.checkEq("isExpert", p.isExpert(), childFlag); Checker.checkEq("isHidden", p.isHidden(), childFlag); Checker.checkEq("isPreferred", p.isPreferred(), childFlag); Checker.checkEq("required", p.getValue("required"), childFlag); Checker.checkEq("visualUpdate", p.getValue("visualUpdate"), childFlag); Checker.checkEnumEq("enumerationValues", p.getValue("enumerationValues"), new Object[]{"BOTTOM", 3, "javax.swing.SwingConstants.BOTTOM"}); }
private void _setPropertySetters(Class<?> klass, List<Object> props) throws IntrospectionException { BeanInfo beanInfo = Introspector.getBeanInfo(klass); PropertyDescriptor[] descs = beanInfo.getPropertyDescriptors(); for(int i=0, sz=props.size(); i<sz; i++) { String name = (String)props.get(i); PropertyDescriptor desc = _getDescriptor(descs, name); if (desc == null) { throw new IllegalArgumentException("property:"+name+" not found on:" +klass); } Method setter = desc.getWriteMethod(); if (setter == null) { throw new IllegalArgumentException("No way to set property:"+name+" on:" +klass); } props.set(i, setter); } }
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); }
/** * 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 ); } }
/** * 将对象转为Map,为null的字段跳过,同时保持有序 * @param bean * @return * @throws IntrospectionException * @throws IllegalAccessException * @throws InvocationTargetException */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static Map bean2MapNull(Object bean) throws IntrospectionException, IllegalAccessException, InvocationTargetException { Class type = bean.getClass(); Map returnMap = new TreeMap(); BeanInfo beanInfo = Introspector.getBeanInfo(type); PropertyDescriptor[] propertyDescriptors = beanInfo .getPropertyDescriptors(); for (int i = 0; i < propertyDescriptors.length; i++) { PropertyDescriptor descriptor = propertyDescriptors[i]; String propertyName = descriptor.getName(); if (!propertyName.equals("class")) { Method readMethod = descriptor.getReadMethod(); Object result = readMethod.invoke(bean, new Object[0]); if (result != null) { returnMap.put(propertyName, result); } else { //没有值的字段直接跳过 } } } return returnMap; }
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; }
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)); }
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)); // System.err.println(" item text is " + item.getText()); 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; // System.err.println("action " + action + (enabled ? " enabled" : " disabled")); item.setEnabled(enabled); boolean visible = (state & ActionProvider.STATE_VISIBLE) != 0; // System.err.println("action " + action + (visible ? " visible" : " invisible")); item.setVisible(visible); item.setMnemonic(provider.getMnemonic(action, containerCtx)); item.setDisplayedMnemonicIndex(provider.getMnemonicIndex(action, containerCtx)); item.setIcon(provider.getIcon(action, containerCtx, BeanInfo.ICON_COLOR_16x16)); }
public void testIconOfTheNode() throws Exception { LogRecord r = new LogRecord(Level.INFO, "icon_msg"); r.setResourceBundleName("org.netbeans.modules.uihandler.TestBundle"); r.setResourceBundle(ResourceBundle.getBundle("org.netbeans.modules.uihandler.TestBundle")); r.setParameters(new Object[] { new Integer(1), "Ahoj" }); Node n = UINode.create(r); assertEquals("Name is taken from the message", "icon_msg", n.getName()); if (!n.getDisplayName().matches(".*Ahoj.*")) { fail("wrong display name, shall contain Ahoj: " + n.getDisplayName()); } Image img = n.getIcon(BeanInfo.ICON_COLOR_32x32); assertNotNull("Some icon", img); IconInfo imgReal = new IconInfo(img); IconInfo template = new IconInfo(getClass().getResource("testicon.png")); assertEquals("Icon from ICON_BASE used", template, imgReal); assertSerializedWell(n); }
/** * 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); }
/** * 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; }
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"); } }
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"}); }
public static void apply ( final Map<String, Variant> data, final Object target, final WriteAttributeResults results ) throws IntrospectionException { final BeanInfo bi = Introspector.getBeanInfo ( target.getClass () ); for ( final Map.Entry<String, Variant> entry : data.entrySet () ) { final PropertyDescriptor pd = findDescriptor ( bi, entry.getKey () ); if ( pd != null ) { try { applyValue ( target, pd, entry.getValue () ); results.put ( entry.getKey (), WriteAttributeResult.OK ); } catch ( final Exception e ) { results.put ( entry.getKey (), new WriteAttributeResult ( e ) ); } } else { results.put ( entry.getKey (), new WriteAttributeResult ( new IllegalArgumentException ( String.format ( "'%s' is not a property name of '%s'", entry.getKey (), target.getClass ().getName () ) ) ) ); } } }
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; }
/** * Introspect on a Java bean and learn about all its properties, exposed * methods, and events, subnject to some comtrol flags. * * @param beanClass The bean class to be analyzed. * @param flags Flags to control the introspection. * If flags == USE_ALL_BEANINFO then we use all of the BeanInfo * classes we can discover. * If flags == IGNORE_IMMEDIATE_BEANINFO then we ignore any * BeanInfo associated with the specified beanClass. * If flags == IGNORE_ALL_BEANINFO then we ignore all BeanInfo * associated with the specified beanClass or any of its * parent classes. * @return A BeanInfo object describing the target bean. * @exception IntrospectionException if an exception occurs during * introspection. */ public static BeanInfo getBeanInfo( Class<?> beanClass, int flags ) throws IntrospectionException { // if they want all of the bean info, call the caching version of this // method so that we cache the result if (flags == USE_ALL_BEANINFO) { return getBeanInfo(beanClass); } else { // // use the uncached version // return new JavaIntrospector(beanClass, null, flags)._getBeanInfo(); } }
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; }
@Override public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object base) { if (base == null) { return null; } try { BeanInfo info = Introspector.getBeanInfo(base.getClass()); PropertyDescriptor[] pds = info.getPropertyDescriptors(); for (int i = 0; i < pds.length; i++) { pds[i].setValue(RESOLVABLE_AT_DESIGN_TIME, Boolean.TRUE); pds[i].setValue(TYPE, pds[i].getPropertyType()); } return Arrays.asList((FeatureDescriptor[]) pds).iterator(); } catch (IntrospectionException e) { // } return null; }
@Override public void performHelp() { String href = null; BeanInfo bi = getCurrentSelectedBeanInfo(); if (bi != null) { String displayName = bi.getBeanDescriptor().getDisplayName(); if ((displayName != null) && !displayName.equals("")) href = getBeanHelpHref(displayName); } if ((href == null) || href.equals("")) href = "convertigoObjects.html"; String helpPageUri = "/com.twinsoft.convertigo.studio.help/help/helpRefManual/"+ href; PlatformUI.getWorkbench().getHelpSystem().displayHelpResource(helpPageUri); }
private static Method getAccessMethod(Object o, String name) { Map<String, Method> methods = beanAccessMethodCache.get(o.getClass()); if (methods == null) { methods = new HashMap<>(); try { BeanInfo beanInfo = Introspector.getBeanInfo(o.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { Method readMethod = propertyDescriptor.getReadMethod(); if (readMethod != null) { methods.put(propertyDescriptor.getName().toLowerCase(), readMethod); } } } catch (IntrospectionException e) { log.warn("Introspection Exception", e); } synchronized (beanAccessMethodCache) { beanAccessMethodCache.put(o.getClass(), methods); } } return methods.get(name.toLowerCase()); }
private void autowiredByName(Bean bean) { try { BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClazz()); PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor desc : descriptors) { for (Bean definedBean : beanDefinitionList) { if (desc.getName().equals(definedBean.getName())) { desc.getWriteMethod().invoke(bean.getObject(), createBean(definedBean) ); break; } } } } catch (Exception e) { throw new BeansException(e); } }
private void autowiredByType(Bean bean) { try { BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClazz()); PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors(); PropertyDescriptor usePd = null; List<Bean> foundBeans = new ArrayList<Bean>(); for (PropertyDescriptor desc : descriptors) { for (Bean definedBean : beanDefinitionList) { if (desc.getPropertyType().equals(definedBean.getClazz())) { foundBeans.add(definedBean); usePd = desc; } } } if (!foundBeans.isEmpty()) { if (foundBeans.size() > 1) throw new BeansException("too many"); usePd.getWriteMethod().invoke(bean.getObject(), createBean(foundBeans.get(0)) ); } } catch (Exception e) { throw new BeansException(e); } }
/** * Sets the values for more parameters for a resource in one step. * * @param parameters a feature map that has parameter names as keys and * parameter values as values. */ public static void setParameterValues(Resource resource, FeatureMap parameters) throws ResourceInstantiationException{ // get the beaninfo for the resource bean, excluding data about Object BeanInfo resBeanInf = null; try { resBeanInf = getBeanInfo(resource.getClass()); } catch(Exception e) { throw new ResourceInstantiationException( "Couldn't get bean info for resource " + resource.getClass().getName() + Strings.getNl() + "Introspector exception was: " + e ); } Iterator<Object> parnameIter = parameters.keySet().iterator(); while(parnameIter.hasNext()){ String parName = (String)parnameIter.next(); setParameterValue(resource, resBeanInf, parName, parameters.get(parName)); } }
public static void main(final String[] args) throws Exception { final BeanInfo beanInfo = Introspector.getBeanInfo(Sub.class); final PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors(); for (final PropertyDescriptor pd : pds) { System.err.println("pd = " + pd); final Class<?> type = pd.getPropertyType(); if (type != Class.class && type != Long[].class && type != Integer.class && type != Enum.class) { throw new RuntimeException(Arrays.toString(pds)); } } }
public static PropertyDescriptor[] propertyDescriptors(Class<?> c) { BeanInfo beanInfo = null; try { beanInfo = Introspector.getBeanInfo(c); } catch (IntrospectionException e) { e.printStackTrace(); } return beanInfo.getPropertyDescriptors(); }
private static List<Variable> paserClass(String path,Class<?> cls, Collection<Class<?>> parsed) throws Exception{ List<Variable> variables=new ArrayList<Variable>(); BeanInfo beanInfo=Introspector.getBeanInfo(cls,Object.class); PropertyDescriptor[] pds= beanInfo.getPropertyDescriptors(); if(pds!=null && !parsed.contains(cls)){ parsed.add(cls); for(PropertyDescriptor pd:pds){ Variable variable=new Variable(); Class<?> type=pd.getPropertyType(); Datatype dataType=getDateType(type); String propertyName=pd.getName(); String label=getPropertyAnnotationLabel(cls, propertyName); String name=path+pd.getName(); variable.setName(name); variable.setLabel(label==null?name:label); variable.setType(dataType); variable.setAct(Act.InOut); if(Datatype.Object.equals(dataType)){ variables.addAll(paserClass(path+pd.getName()+".",type, parsed)); }else{ variables.add(variable); } } } return variables; }
@Override public void processBeanInfo(BeanInfo beanInfo) throws Exception { for ( PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors() ) { if ( propertyDescriptor.getName().equals( attributeName ) ) { javaType = propertyDescriptor.getPropertyType(); break; } } }
/** * @desc 根据对象获取对象所有属性、属性值 * * @author liuliang * * @param entity 对象 * @return Map<String,Object> [key:属性名 value:属性名对应的值] */ public static Map<String,Object> getBeanInfo(Object entity){ Map<String,Object> map = new HashMap<String, Object>(16); try { Class<?> clazz = entity.getClass(); BeanInfo beanInfo = null; if(null == methodCache.get(clazz)){ Class<?> superClazz =clazz.getSuperclass(); beanInfo = Introspector.getBeanInfo(clazz, superClazz); methodCache.put(clazz, beanInfo); Introspector.flushFromCaches(clazz); if(null != superClazz){ Introspector.flushFromCaches(superClazz); } }else{ beanInfo = methodCache.get(clazz); } PropertyDescriptor[] pdArr = beanInfo.getPropertyDescriptors(); for(PropertyDescriptor pd:pdArr){ String fieldName = pd.getName(); Object fieldValue = getFieldValue(pd.getReadMethod(),entity); map.put(fieldName, fieldValue); } } catch (IntrospectionException e) { logger.error("获取对象信息异常,entity:{}",entity.getClass(),e); } return map; }
@Test public void getterFunctionTest() throws IntrospectionException { final BeanInfo beanInfo = Introspector.getBeanInfo(GetterFunction.class); final Method applyMethod = Arrays.asList(beanInfo.getMethodDescriptors()) .stream() .map(md -> md.getMethod()) .filter(m -> m.getName().equals("apply")) .findAny() .get(); final Class<?>[] parameterTypes = applyMethod.getParameterTypes(); final Class<?> returnType = applyMethod.getReturnType(); assertTrue(true); }
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); } }