Bean Utility : Java Beans « Development Class « Java






Bean Utility

   
/*
 * StringUtil.java
 *
 * Created on May 7, 2004, 7:43 PM
 *
 * Copyright (C) 2004  Robert Cooper, Temple of the Screaming Penguin
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
import java.beans.*;
import java.lang.reflect.*;

/** This class contains some generic methods for working with String.
 * @version $Rev: 87 $
 * @author  <a href="mailto:cooper@screaming-penguin.com">Robert Cooper</a>
 */
public class BeanUtility {
    
    /** Creates a new instance of StringUtil */
    private BeanUtility() { }
    
    /** This method takes a JavaBean and generates a standard toString() type result for it.
     * @param o JavaBean object to stringinate
     * @return STRINGIATION! Stringingating the countryside. Stringinating all the peasants.
     */
    public static String beanToString( Object o ){
        StringBuffer result = new StringBuffer();
        if(o == null)
            return "--- null";
        result.append( "--- begin");result.append( o.getClass().getName()); result.append(" hash: ");
        result.append( o.hashCode() ); result.append( "\r\n");
        try{
            PropertyDescriptor[] pds = Introspector.getBeanInfo( o.getClass() ).getPropertyDescriptors();
            for( int pdi = 0; pdi < pds.length; pdi ++ ){
                try{
                    result.append( "Property: "+ pds[pdi].getName() + " Value: " + pds[pdi].getReadMethod().invoke( o ) );
                } catch( IllegalAccessException iae ){
                    result.append( "Property: "+ pds[pdi].getName() + " (Illegal Access to Value) ");
                }
                catch( InvocationTargetException iae ){
                    result.append( "Property: "+ pds[pdi].getName() + " (InvocationTargetException) " + iae.toString() );
                }
                catch( Exception e ){
                     result.append( "Property: "+ pds[pdi].getName() +" (Other Exception )"+e.toString());
                }
                result.append( "\r\n");
            }
            
            
        } catch( IntrospectionException ie){
            result.append( "Introspection Exception: " + ie.toString() ); result.append( "\r\n");
        }
        result.append( "--- end " ); result.append( o.getClass().getName()); result.append(" hash: ");
        result.append( o.hashCode() ); result.append( "\n");
        return result.toString();
    }
    
    /** This method takes 2 JavaBeans of the same type and copies the properties of one bean to the other.
     * Any attempts that have an IllegalAccessException will be ignored. This will also NOT recurse into nested bean
     * results. References to existing beanage will be includes. Try using .clone() for that stuff.
     * @param from Source Bean
     * @param to Desitnation Bean
     */
    public static void copyBeanToBean( Object from, Object to ) throws InvocationTargetException, IntrospectionException{
        PropertyDescriptor[] pds = Introspector.getBeanInfo( from.getClass() ).getPropertyDescriptors();
        for( int i=0; i < pds.length; i++){
            try{
                if(pds[i].getName().equals("class")) continue;
                Object[] value = {pds[i].getReadMethod().invoke(from) };
                pds[i].getWriteMethod().invoke( to, value ) ;
            } catch( IllegalAccessException iae ){
                //Im just going to ignore any properties I don't have access too.
            }
        }
        
    }
    
    public static String[] getPropertyNames(Object o) throws IntrospectionException {
        PropertyDescriptor[] pds = Introspector.getBeanInfo( o.getClass() ).getPropertyDescriptors();
        String[] propertyNames = new String[ pds.length];
        for( int i=0; i< pds.length; i++){
            propertyNames[i] = pds[i].getName();
        }
        return propertyNames;
    }
    
    public static Object getProperty( Object o, String propertyName ) throws Exception {
        PropertyDescriptor[] pds = Introspector.getBeanInfo( o.getClass() ).getPropertyDescriptors();
        for( int i=0; i< pds.length; i++){
            if( pds[i].getName().equals(propertyName)){
                return pds[i].getReadMethod().invoke( o ) ;
            }
        }
        throw new Exception("Property not found.");
    }
    public static void setProperty( Object o, String propertyName, Object value ) throws Exception{
        PropertyDescriptor[] pds = Introspector.getBeanInfo( o.getClass() ).getPropertyDescriptors();
        for( int i=0; i< pds.length; i++){
            if( pds[i].getName().equals(propertyName)){
                pds[i].getWriteMethod().invoke( o, value );
                return;
            }
        }
        throw new Exception("Property not found.");
    }
    
    public static Class getPropertyType( Object o, String propertyName ) throws Exception{
        PropertyDescriptor[] pds = Introspector.getBeanInfo( o.getClass() ).getPropertyDescriptors();
        for( int i=0; i< pds.length; i++){
            if( pds[i].getName().equals(propertyName)){
                return pds[i].getPropertyType();
            }
        }
        throw new Exception("Property not found.");
    }
}

   
    
    
  








Related examples in the same category

1.JavaBean: BeanContextSupportJavaBean: BeanContextSupport
2.JavaBean: Test program that adds 100 beans to a contextJavaBean: Test program that adds 100 beans to a context
3.JavaBean: how to use the instantiateChild() convenience method to create a beanJavaBean: how to use the instantiateChild() convenience method to create a bean
4.JavaBean: illustrate delivery of the BeanContextMembershipEventJavaBean: illustrate delivery of the BeanContextMembershipEvent
5.JavaBean: creates all of the objects, a tests the service capabilitiesJavaBean: creates all of the objects, a tests the service capabilities
6.Bean ContainerBean Container
7.PropertyTablePropertyTable
8.Introspecting a BeanIntrospecting a Bean
9.Listening for Changes to the Selected File in a JFileChooser Dialog
10.Get a list of selected files
11.Listening for Changes to the Current Directory in a JFileChooser Dialog
12.Displaying the Current Directory in the Title of a JFileChooser Dialog
13.Setting an Accessory Component in a JFileChooser Dialog
14.Convert a bean to XML persistence
15.Listen for bean's property change event
16.List property names of a Bean
17.Prevent bean's property being serialized to XML
18.Create an instance a Bean
19.Convert an XML persistence to bean
20.Determine bean's property type
21.Listen for a constrained property change
22.Bean has a single property called property.
23.Implementing a Bound Property
24.Implementing a Constrained Property: fires a PropertyChangeEvent whenever its value is about to be changed.
25.Instantiating a Bean
26.Listing the Property Names of a Bean
27.Getting and Setting a Property of a Bean
28.Get and set the value of a property in a bean using Expression and Statement
29.Get and set an Object type property
30.gets and sets a primitive type property
31.gets and sets an array type property
32.Serializing a Bean to XML: XMLEncoder only persists the value of public properties.
33.Deserializing a Bean from XML
34.Preventing a Bean Property from Being Serialized to XML
35.Serializing an Immutable Bean Property to XML
36.Listening for a Property Change Event: A property change event is fired when a bound property is changed.
37.Listening for a Vetoable Property Change Event
38.Read bean's property value
39.Saving and restoring the state of a pretend CAD systemSaving and restoring the state of a pretend CAD system
40.An extension of ArrayList that provides some handy utilities for working with JavaBeans
41.An extension of Vector that provides some handy utilities for working with JavaBeans
42.extends SimpleBeanInfo
43.Get and set properties on a bean
44.Is JavaBean Compliant Setter
45.This program demonstrates the use of an XML encoder and decoder to save and restore a frame.
46.This program demonstrates various persistence delegates.
47.Event Tracer