Java Tutorial/Development/JavaBeans — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Версия 17:44, 31 мая 2010
Содержание
- 1 Bean has a single property called property.
- 2 Constructs a method name from element"s bean name for a given prefix
- 3 Convert a bean to XML persistence
- 4 Convert an XML persistence to bean
- 5 Create an instance a Bean
- 6 Deserializing a Bean from XML
- 7 Determine bean"s property type
- 8 Displaying the Current Directory in the Title of a JFileChooser Dialog
- 9 extends SimpleBeanInfo
- 10 Get a list of selected files
- 11 Get and set an Object type property
- 12 Get and set properties on a bean
- 13 Get and set the value of a property in a bean using Expression and Statement
- 14 gets and sets an array type property
- 15 gets and sets a primitive type property
- 16 Getting and Setting a Property of a Bean
- 17 Implementing a Bound Property
- 18 Implementing a Constrained Property: fires a PropertyChangeEvent whenever its value is about to be changed.
- 19 Instantiating a Bean
- 20 Is JavaBean Compliant Setter
- 21 Listen for a constrained property change
- 22 Listen for bean"s property change event
- 23 Listening for a Property Change Event: A property change event is fired when a bound property is changed.
- 24 Listening for a Vetoable Property Change Event
- 25 Listening for Changes to the Current Directory in a JFileChooser Dialog
- 26 Listening for Changes to the Selected File in a JFileChooser Dialog
- 27 Listing the Property Names of a Bean
- 28 List property names of a Bean
- 29 Prevent bean"s property being serialized to XML
- 30 Preventing a Bean Property from Being Serialized to XML
- 31 Process bean properties getter by applying the JavaBean naming conventions.
- 32 Read bean"s property value
- 33 Returns attribute"s setter method. If the method not found then NoSuchMethodException will be thrown.
- 34 Serializing a Bean to XML: XMLEncoder only persists the value of public properties.
- 35 Serializing an Immutable Bean Property to XML
- 36 Setting an Accessory Component in a JFileChooser Dialog
Bean has a single property called property.
import java.io.Serializable;
public class BasicBean implements Serializable {
boolean property;
public BasicBean() {
}
public boolean getProperty() {
return property;
}
public boolean isProperty() {
return property;
}
public void setProperty(boolean newValue) {
property = newValue;
}
}
Constructs a method name from element"s bean name for a given prefix
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don"t indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
/**
*
* @author Rajeshwar Patil
* @version %I%, %G%
*/
public class Utils {
/**
* Constructs a method name from element"s bean
* name for a given prefix.(schema2beans convention)
*
* @param elementName the given element name
* @param prefix the given prefix
* @return a method name formed from the given name and the prefix
*/
public String methodNameFromBeanName(String elementName,
String prefix){
if((null == elementName) || (null == prefix) ||
(prefix.length() <= 0 )){
return elementName;
}
String methodName = upperCaseFirstLetter(elementName);
return methodName = prefix + methodName;
}
/**
* Converts the first letter of the given string to Uppercase.
*
* @param string the input string
* @return the string with the Uppercase first letter
*/
public String upperCaseFirstLetter(String string)
{
if(string == null || string.length() <= 0){
return string;
}
return string.substring(0, 1).toUpperCase() + string.substring(1);
}
}
Convert a bean to XML persistence
import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
public class Main {
public static void main(String[] args) throws Exception {
Item bean = new Item();
bean.setId(new Long(1));
bean.setItemName("a");
bean.setItemColour("Red");
bean.setItemQuantities(new Integer(100));
XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream("Bean.xml")));
encoder.writeObject(bean);
encoder.close();
}
}
class Item {
private Long id;
private String itemName;
private String itemColour;
private Integer itemQuantities;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemColour() {
return itemColour;
}
public void setItemColour(String itemColour) {
this.itemColour = itemColour;
}
public Integer getItemQuantities() {
return itemQuantities;
}
public void setItemQuantities(Integer itemQuantities) {
this.itemQuantities = itemQuantities;
}
}
Convert an XML persistence to bean
import java.beans.XMLDecoder;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.Serializable;
public class Main {
public static void main(String[] argv) throws Exception {
XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(new FileInputStream("Bean.xml")));
Bean bean = (Bean) decoder.readObject();
decoder.close();
System.out.println("ID = " + bean.getId());
}
}
class Bean implements Serializable {
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
Here is our Bean.xml persistence file:
<?xml version="1.0" encoding="UTF-8"?>
<java version="1.6.0_02" class="java.beans.XMLDecoder">
<object class="org.username.example.bean.BeanToXML">
<void property="id">
<long>1</long>
</void>
</object>
</java>
Create an instance a Bean
import java.beans.Beans;
import java.io.Serializable;
public class Main implements Serializable {
private Long id;
private String name;
public Main() {
}
public static void main(String[] args) throws Exception {
Main bean = (Main) Beans.instantiate(ClassLoader.getSystemClassLoader(),
"Main");
System.out.println("The Bean = " + bean);
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "[id=" + id + "; name=" + name + "]";
}
}
Deserializing a Bean from XML
import java.beans.XMLDecoder;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
public class Main {
public static void main(String[] argv) throws Exception {
XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(
new FileInputStream("infilename.xml")));
MyClass o = (MyClass) decoder.readObject();
decoder.close();
int prop = o.getProp(); // 1
int[] props = o.getProps(); // [1, 2, 3]
}
}
class MyClass {
// The prop property
int i;
public int getProp() {
return i;
}
public void setProp(int i) {
this.i = i;
}
// The props property
int[] iarray = new int[0];
public int[] getProps() {
return iarray;
}
public void setProps(int[] iarray) {
this.iarray = iarray;
}
}
/*
<?xml version="1.0" encoding="UTF-8"?>
<java version="1.4.0" class="java.beans.XMLDecoder">
<object class="MyClass">
<void property="prop">
<int>1</int>
</void>
<void property="props">
<array class="int" length="3">
<void index="0">
<int>1</int>
</void>
<void index="1">
<int>2</int>
</void>
<void index="2">
<int>3</int>
</void>
</array>
</void>
</object>
</java>
*/
Determine bean"s property type
import org.apache.rumons.beanutils.PropertyUtils;
public class Main {
public static void main(String[] args) throws Exception {
Recording recording = new Recording();
recording.setTitle("Magical Mystery Tour");
Class type = PropertyUtils.getPropertyType(recording, "title");
System.out.println("type = " + type.getName());
String value = (String) PropertyUtils.getProperty(recording, "title");
System.out.println("value = " + value);
}
}
Displaying the Current Directory in the Title of a JFileChooser Dialog
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import javax.swing.JFileChooser;
public class Main {
public static void main(String[] argv) {
final JFileChooser chooser = new JFileChooser();
File curDir = chooser.getCurrentDirectory();
chooser.setDialogTitle("" + curDir.getAbsolutePath());
chooser.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(evt.getPropertyName())) {
File curDir = chooser.getCurrentDirectory();
chooser.setDialogTitle("" + curDir.getAbsolutePath());
}
}
});
}
}
extends SimpleBeanInfo
/**
* FontSelectorBeanBeanInfo.java 1.00 97/08/09 Merlin Hughes
*
* Copyright (c) 1997 Merlin Hughes, All Rights Reserved.
*
* Permission to use, copy, modify, and distribute this software
* for commercial and non-commercial purposes and without fee is
* hereby granted provided that this copyright notice appears in
* all copies.
*
* http://prominence.ru/ ego@merlin.org
*/
import java.awt.Image;
import java.beans.SimpleBeanInfo;
public class FontSelectorBeanBeanInfo extends SimpleBeanInfo {
public Image getIcon(int iconKind) {
if (iconKind == ICON_COLOR_16x16) {
return loadImage("FontSelectorBeanIconColor16.gif");
} else {
return null;
}
}
}
Get a list of selected files
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import javax.swing.JFileChooser;
public class Main {
public static void main(String[] argv) throws Exception {
JFileChooser chooser = new JFileChooser();
chooser.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (JFileChooser.SELECTED_FILES_CHANGED_PROPERTY.equals(evt.getPropertyName())) {
JFileChooser chooser = (JFileChooser) evt.getSource();
File[] oldFiles = (File[]) evt.getOldValue();
File[] newFiles = (File[]) evt.getNewValue();
// Get list of selected files
File[] files = chooser.getSelectedFiles();
}
}
});
}
}
Get and set an Object type property
import java.beans.Expression;
import java.beans.Statement;
public class Main {
public static void main(String[] argv) throws Exception {
Object o = new MyBean();
// Get the value of prop1
Expression expr = new Expression(o, "getProp1", new Object[0]);
expr.execute();
String s = (String) expr.getValue();
// Set the value of prop1
Statement stmt = new Statement(o, "setProp1", new Object[] { "new string" });
stmt.execute();
}
}
class MyBean {
String prop1;
public String getProp1() {
return prop1;
}
public void setProp1(String s) {
prop1 = s;
}
int prop2;
public int getProp2() {
return prop2;
}
public void setProp2(int i) {
prop2 = i;
}
byte[] prop3;
public byte[] getProp3() {
return prop3;
}
public void setProp3(byte[] bytes) {
prop3 = bytes;
}
}
Get and set properties on a bean
/*
* The contents of this file are subject to the Sapient Public License
* Version 1.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://carbon.sf.net/License.html.
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* The Original Code is The Carbon Component Framework.
*
* The Initial Developer of the Original Code is Sapient Corporation
*
* Copyright (C) 2003 Sapient Corporation. All Rights Reserved.
*/
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.StringTokenizer;
/**
* This class implements the ability to get and set properties on a
* bean. This included the concept of embedded properties that may
* be referenced like <code>Bean.property.property.property</code>.
*
* Copyright 2002 Sapient
* @since carbon 1.0
* @author Greg Hinkle, January 2002
* @version $Revision: 1.11 $ ($Author: dvoet $)
*/
public final class BeanUtil {
/**
* String used to separate multiple properties inside of embedded
* beans.
*/
private static final String PROPERTY_SEPARATOR = ".";
/**
* An empty class array used for null parameter method reflection
*/
private static Class[] NO_PARAMETERS_ARRAY = new Class[] {
};
/**
* an empty object array used for null parameter method reflection
*/
private static Object[] NO_ARGUMENTS_ARRAY = new Object[] {
};
/**
* The constructor is private so that <tt>new</tt> cannot be used.
*/
private BeanUtil() {
}
/**
* Retreives a property descriptor object for a given property.
*
* Uses the classes in <code>java.beans</code> to get back
* a descriptor for a property. Read-only and write-only
* properties will have a slower return time.
*
*
* @param propertyName The programmatic name of the property
* @param beanClass The Class object for the target bean.
* For example sun.beans.OurButton.class.
* @return a PropertyDescriptor for a property that follows the
* standard Java naming conventions.
* @throws PropertyNotFoundException indicates that the property
* could not be found on the bean class.
*/
private static final PropertyDescriptor getPropertyDescriptor(
String propertyName,
Class beanClass) {
PropertyDescriptor resultPropertyDescriptor = null;
char[] pNameArray = propertyName.toCharArray();
pNameArray[0] = Character.toLowerCase(pNameArray[0]);
propertyName = new String(pNameArray);
try {
resultPropertyDescriptor =
new PropertyDescriptor(propertyName, beanClass);
} catch (IntrospectionException e1) {
// Read-only and write-only properties will throw this
// exception. The properties must be looked up using
// brute force.
// This will get the list of all properties and iterate
// through looking for one that matches the property
// name passed into the method.
try {
BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
PropertyDescriptor[] propertyDescriptors =
beanInfo.getPropertyDescriptors();
for (int i = 0; i < propertyDescriptors.length; i++) {
if (propertyDescriptors[i]
.getName()
.equals(propertyName)) {
// If the names match, this this describes the
// property being searched for. Break out of
// the iteration.
resultPropertyDescriptor = propertyDescriptors[i];
break;
}
}
} catch (IntrospectionException e2) {
e2.printStackTrace();
}
}
// If no property descriptor was found, then this bean does not
// have a property matching the name passed in.
if (resultPropertyDescriptor == null) {
System.out.println("resultPropertyDescriptor == null");
}
return resultPropertyDescriptor;
}
/**
* Gets the specified attribute from the specified object. For example,
* <code>getObjectAttribute(o, "address.line1")</code> will return
* the result of calling <code>o.getAddress().getLine1()</code>.
*
* The attribute specified may contain as many levels as you like. If at
* any time a null reference is acquired by calling one of the successive
* getter methods, then the return value from this method is also null.
*
* When reading from a boolean property the underlying bean introspector
* first looks for an is<Property> read method, not finding one it will
* still look for a get<Property> read method. Not finding either, the
* property is considered write-only.
*
* @param bean the bean to set the property on
* @param propertyNames the name of the propertie(s) to retrieve. If this is
* null or the empty string, then <code>bean</code> will be returned.
* @return the object value of the bean attribute
*
* @throws PropertyNotFoundException indicates the the given property
* could not be found on the bean
* @throws NoSuchMethodException Not thrown
* @throws InvocationTargetException if a specified getter method throws an
* exception.
* @throws IllegalAccessException if a getter method is
* not public or property is write-only.
*/
public static Object getObjectAttribute(Object bean, String propertyNames)
throws
NoSuchMethodException,
InvocationTargetException,
IllegalAccessException {
Object result = bean;
StringTokenizer propertyTokenizer =
new StringTokenizer(propertyNames, PROPERTY_SEPARATOR);
// Run through the tokens, calling get methods and
// replacing result with the new object each time.
// If the result equals null, then simply return null.
while (propertyTokenizer.hasMoreElements() && result != null) {
Class resultClass = result.getClass();
String currentPropertyName = propertyTokenizer.nextToken();
PropertyDescriptor propertyDescriptor =
getPropertyDescriptor(currentPropertyName, resultClass);
Method readMethod = propertyDescriptor.getReadMethod();
if (readMethod == null) {
throw new IllegalAccessException(
"User is attempting to "
+ "read from a property that has no read method. "
+ " This is likely a write-only bean property. Caused "
+ "by property ["
+ currentPropertyName
+ "] on class ["
+ resultClass
+ "]");
}
result = readMethod.invoke(result, NO_ARGUMENTS_ARRAY);
}
return result;
}
/**
* Sets the specified attribute on the specified object. For example,
* <code>getObjectAttribute(o, "address.line1", value)</code> will call
* <code>o.getAddress().setLine1(value)</code>.
*
* The attribute specified may contain as many levels as you like. If at
* any time a null reference is acquired by calling one of the successive
* getter methods, then a <code>NullPointerException</code> is thrown.
*
* @param bean the bean to call the getters on
* @param propertyNames the name of the attribute(s) to set. If this is
* null or the empty string, then an exception is thrown.
* @param value the value of the object to set on the bean property
*
* @throws PropertyNotFoundException indicates the the given property
* could not be found on the bean
* @throws IllegalArgumentException if the supplied parameter is not of
* a valid type
* @throws NoSuchMethodException never
* @throws IllegalAccessException if a getter or setter method is
* not public or property is read-only.
* @throws InvocationTargetException if a specified getter method throws an
* exception.
*/
public static void setObjectAttribute(
Object bean,
String propertyNames,
Object value)
throws
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException,
NoSuchMethodException {
Object result = bean;
String propertyName = propertyNames;
// Check if this has some embedded properties. If it does, use the
// getObjectAttribute to get the proper object to call this on.
int indexOfLastPropertySeparator =
propertyName.lastIndexOf(PROPERTY_SEPARATOR);
if (indexOfLastPropertySeparator >= 0) {
String embeddedProperties =
propertyName.substring(0, indexOfLastPropertySeparator);
// Grab the final property name after the last property separator
propertyName =
propertyName.substring(
indexOfLastPropertySeparator + PROPERTY_SEPARATOR.length());
result = getObjectAttribute(result, embeddedProperties);
}
Class resultClass = result.getClass();
PropertyDescriptor propertyDescriptor =
getPropertyDescriptor(propertyName, resultClass);
Method writeMethod = propertyDescriptor.getWriteMethod();
if (writeMethod == null) {
throw new IllegalAccessException(
"User is attempting to write "
+ "to a property that has no write method. This is likely "
+ "a read-only bean property. Caused by property ["
+ propertyName
+ "] on class ["
+ resultClass
+ "]");
}
writeMethod.invoke(result, new Object[] { value });
}
}
Get and set the value of a property in a bean using Expression and Statement
import java.beans.Expression;
import java.beans.Statement;
public class Main {
public static void main(String[] argv) throws Exception {
Object o = new MyBean();
// Get the value of prop1
Expression expr = new Expression(o, "getProp1", new Object[0]);
expr.execute();
String s = (String) expr.getValue();
// Set the value of prop1
Statement stmt = new Statement(o, "setProp1", new Object[] { "new string" });
stmt.execute();
}
}
class MyBean {
String prop1;
public String getProp1() {
return prop1;
}
public void setProp1(String s) {
prop1 = s;
}
int prop2;
public int getProp2() {
return prop2;
}
public void setProp2(int i) {
prop2 = i;
}
byte[] prop3;
public byte[] getProp3() {
return prop3;
}
public void setProp3(byte[] bytes) {
prop3 = bytes;
}
}
gets and sets an array type property
import java.beans.Expression;
import java.beans.Statement;
public class Main {
public static void main(String[] argv) throws Exception {
Object o = new MyBean();
Expression expr = new Expression(o, "getProp3", new Object[0]);
expr.execute();
byte[] bytes = (byte[]) expr.getValue();
Statement stmt = new Statement(o, "setProp3", new Object[] { new byte[] {
0x12, 0x23 } });
stmt.execute();
}
}
class MyBean {
String prop1;
public String getProp1() {
return prop1;
}
public void setProp1(String s) {
prop1 = s;
}
int prop2;
public int getProp2() {
return prop2;
}
public void setProp2(int i) {
prop2 = i;
}
byte[] prop3;
public byte[] getProp3() {
return prop3;
}
public void setProp3(byte[] bytes) {
prop3 = bytes;
}
}
gets and sets a primitive type property
import java.beans.Expression;
import java.beans.Statement;
public class Main {
public static void main(String[] argv) throws Exception {
Object o = new MyBean();
// Get the value of prop2
Expression expr = new Expression(o, "getProp2", new Object[0]);
expr.execute();
int i = ((Integer) expr.getValue()).intValue();
// Set the value of prop2
Statement stmt = new Statement(o, "setProp2", new Object[] { new Integer(123) });
stmt.execute();
}
}
class MyBean {
String prop1;
public String getProp1() {
return prop1;
}
public void setProp1(String s) {
prop1 = s;
}
int prop2;
public int getProp2() {
return prop2;
}
public void setProp2(int i) {
prop2 = i;
}
byte[] prop3;
public byte[] getProp3() {
return prop3;
}
public void setProp3(byte[] bytes) {
prop3 = bytes;
}
}
Getting and Setting a Property of a Bean
import java.beans.Expression;
import java.beans.Statement;
public class Main {
public static void main(String[] argv) throws Exception {
Object o = new MyBean();
// Get the value of prop1
Expression expr = new Expression(o, "getProp1", new Object[0]);
expr.execute();
String s = (String) expr.getValue();
// Set the value of prop1
Statement stmt = new Statement(o, "setProp1", new Object[] { "new string" });
stmt.execute();
}
}
class MyBean {
String prop1;
public String getProp1() {
return prop1;
}
public void setProp1(String s) {
prop1 = s;
}
int prop2;
public int getProp2() {
return prop2;
}
public void setProp2(int i) {
prop2 = i;
}
byte[] prop3;
public byte[] getProp3() {
return prop3;
}
public void setProp3(byte[] bytes) {
prop3 = bytes;
}
}
Implementing a Bound Property
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
public class MyBean {
PropertyChangeSupport pceListeners = new PropertyChangeSupport(this);
int myProperty;
public int getMyProperty() {
return myProperty;
}
public void setMyProperty(int newValue) {
int oldValue = myProperty;
myProperty = newValue;
pceListeners.firePropertyChange("myProperty", new Integer(oldValue),
new Integer(newValue));
}
public synchronized void addPropertyChangeListener(
PropertyChangeListener listener) {
pceListeners.addPropertyChangeListener(listener);
}
public synchronized void removePropertyChangeListener(
PropertyChangeListener listener) {
pceListeners.removePropertyChangeListener(listener);
}
}
Implementing a Constrained Property: fires a PropertyChangeEvent whenever its value is about to be changed.
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
import java.beans.VetoableChangeSupport;
public class MyBean {
VetoableChangeSupport vceListeners = new VetoableChangeSupport(this);
int myProperty;
public int getMyProperty() {
return myProperty;
}
public void setMyProperty(int newValue) throws PropertyVetoException {
try {
vceListeners.fireVetoableChange("myProperty", new Integer(myProperty),
new Integer(newValue));
myProperty = newValue;
} catch (PropertyVetoException e) {
throw e;
}
}
public synchronized void addVetoableChangeListener(
VetoableChangeListener listener) {
vceListeners.addVetoableChangeListener(listener);
}
public synchronized void removeVetoableChangeListener(
VetoableChangeListener listener) {
vceListeners.removeVetoableChangeListener(listener);
}
}
Instantiating a Bean
import java.beans.Beans;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
import java.beans.VetoableChangeSupport;
public class Main {
public static void main(String[] argv) throws Exception {
MyBean bean = (MyBean) Beans.instantiate(
ClassLoader.getSystemClassLoader(), "MyBean");
}
}
class MyBean {
VetoableChangeSupport vceListeners = new VetoableChangeSupport(this);
int myProperty;
public int getMyProperty() {
return myProperty;
}
public void setMyProperty(int newValue) throws PropertyVetoException {
try {
vceListeners.fireVetoableChange("myProperty", new Integer(myProperty),
new Integer(newValue));
myProperty = newValue;
} catch (PropertyVetoException e) {
throw e;
}
}
public synchronized void addVetoableChangeListener(
VetoableChangeListener listener) {
vceListeners.addVetoableChangeListener(listener);
}
public synchronized void removeVetoableChangeListener(
VetoableChangeListener listener) {
vceListeners.removeVetoableChangeListener(listener);
}
}
Is JavaBean Compliant Setter
import java.lang.reflect.Method;
public class Utils {
public static boolean isJavaBeanCompliantSetter (Method method)
{
if (method == null)
return false;
if (method.getReturnType() != Void.TYPE)
return false;
if (!method.getName().startsWith("set"))
return false;
if (method.getParameterTypes().length != 1)
return false;
return true;
}
}
Listen for a constrained property change
import java.beans.PropertyChangeEvent;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
import java.beans.VetoableChangeSupport;
public class Main {
private double interest;
private VetoableChangeSupport vcs = new VetoableChangeSupport(this);
public Main() {
vcs.addVetoableChangeListener(new VetoChangeListener());
}
public double getInterest() {
return interest;
}
public void setInterest(double interest) {
try {
vcs.fireVetoableChange("interest", new Double(this.interest), new Double(interest));
this.interest = interest;
} catch (PropertyVetoException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Main bean = new Main();
bean.setInterest(10.99);
bean.setInterest(15.99);
bean.setInterest(20.99);
}
}
class VetoChangeListener implements VetoableChangeListener {
public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException {
String eventName = evt.getPropertyName();
if (eventName.equalsIgnoreCase("interest")) {
double interest = ((Double) evt.getNewValue()).doubleValue();
if (interest > 20.00) {
throw new PropertyVetoException("Interest must be below 20.00", evt);
}
System.out.println("Interest applied = " + interest);
}
}
}
Listen for bean"s property change event
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.Serializable;
public class Main {
public static void main(String[] argv) throws Exception {
MyBean bean = new MyBean();
bean.setName("A");
bean.setName("B");
bean.setName("C");
}
}
class MyBean implements PropertyChangeListener, Serializable {
private Long id;
private String name;
private PropertyChangeSupport pcs = new PropertyChangeSupport(this);
public MyBean() {
pcs.addPropertyChangeListener(this);
}
public void propertyChange(PropertyChangeEvent evt) {
System.out.println("Name = " + evt.getPropertyName());
System.out.println("Old Value = " + evt.getOldValue());
System.out.println("New Value = " + evt.getNewValue());
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
String oldValue = this.name;
this.name = name;
pcs.firePropertyChange("name", oldValue, name);
}
}
Listening for a Property Change Event: A property change event is fired when a bound property is changed.
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
public class Main {
public static void main(String[] argv) throws Exception {
MyBean bean = new MyBean();
bean.addPropertyChangeListener(new MyPropertyChangeListener());
}
}
class MyPropertyChangeListener implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent evt) {
Object oldValue = evt.getOldValue();
Object newValue = evt.getNewValue();
}
}
class MyBean {
PropertyChangeSupport pceListeners = new PropertyChangeSupport(this);
int myProperty;
public int getMyProperty() {
return myProperty;
}
public void setMyProperty(int newValue) {
int oldValue = myProperty;
myProperty = newValue;
pceListeners.firePropertyChange("myProperty", new Integer(oldValue),
new Integer(newValue));
}
public synchronized void addPropertyChangeListener(
PropertyChangeListener listener) {
pceListeners.addPropertyChangeListener(listener);
}
public synchronized void removePropertyChangeListener(
PropertyChangeListener listener) {
pceListeners.removePropertyChangeListener(listener);
}
}
Listening for a Vetoable Property Change Event
// A vetoable property change event is fired when a constrained property is changed.
// A listener can veto the change by throwing PropertyVetoException and preventing the change.
import java.beans.PropertyChangeEvent;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
import java.beans.VetoableChangeSupport;
public class Main {
public static void main(String[] argv) throws Exception {
MyBean bean = new MyBean();
bean.addVetoableChangeListener(new MyVetoableChangeListener());
}
}
class MyVetoableChangeListener implements VetoableChangeListener {
public void vetoableChange(PropertyChangeEvent evt)
throws PropertyVetoException {
Object oldValue = evt.getOldValue();
Object newValue = evt.getNewValue();
boolean veto = false;
if (veto) {
throw new PropertyVetoException("the reason for the veto", evt);
}
}
}
class MyBean {
VetoableChangeSupport vceListeners = new VetoableChangeSupport(this);
int myProperty;
public int getMyProperty() {
return myProperty;
}
public void setMyProperty(int newValue) throws PropertyVetoException {
try {
vceListeners.fireVetoableChange("myProperty", new Integer(myProperty),
new Integer(newValue));
myProperty = newValue;
} catch (PropertyVetoException e) {
throw e;
}
}
public synchronized void addVetoableChangeListener(
VetoableChangeListener listener) {
vceListeners.addVetoableChangeListener(listener);
}
public synchronized void removeVetoableChangeListener(
VetoableChangeListener listener) {
vceListeners.removeVetoableChangeListener(listener);
}
}
Listening for Changes to the Current Directory in a JFileChooser Dialog
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import javax.swing.JFileChooser;
public class Main {
public static void main(String[] argv) throws Exception {
final JFileChooser chooser = new JFileChooser();
chooser.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(evt.getPropertyName())) {
JFileChooser chooser = (JFileChooser) evt.getSource();
File oldDir = (File) evt.getOldValue();
File newDir = (File) evt.getNewValue();
File curDir = chooser.getCurrentDirectory();
}
}
});
}
}
Listening for Changes to the Selected File in a JFileChooser Dialog
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import javax.swing.JFileChooser;
public class Main {
public static void main(String[] argv) throws Exception {
JFileChooser chooser = new JFileChooser();
chooser.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(evt.getPropertyName())) {
JFileChooser chooser = (JFileChooser) evt.getSource();
File oldFile = (File) evt.getOldValue();
File newFile = (File) evt.getNewValue();
File curFile = chooser.getSelectedFile();
}
}
});
}
}
Listing the Property Names of a Bean
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
public class Main {
public static void main(String[] argv) throws Exception {
BeanInfo bi = Introspector.getBeanInfo(MyBean.class);
PropertyDescriptor[] pds = bi.getPropertyDescriptors();
for (int i = 0; i < pds.length; i++) {
String propName = pds[i].getDisplayName();
System.out.println(propName);
}
}
}
class MyBean {
public String getProp1() {
return null;
}
public void setProp1(String s) {
}
public int getProp2() {
return 0;
}
public void setProp2(int i) {
}
public byte[] getPROP3() {
return null;
}
public void setPROP3(byte[] bytes) {
}
}
List property names of a Bean
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.Serializable;
public class Main {
public static void main(String[] argv) throws Exception {
BeanInfo beanInfo = Introspector.getBeanInfo(Fruit.class);
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor pd : pds) {
String propertyName = pd.getName();
System.out.println("propertyName = " + propertyName);
}
}
}
class Fruit implements Serializable {
private Long id;
private String name;
private double price;
public Fruit() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
Prevent bean"s property being serialized to XML
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
public class Main {
public static void main(String[] argv) throws Exception {
BeanInfo bi = Introspector.getBeanInfo(BeanToXmlTransient.class);
PropertyDescriptor[] pds = bi.getPropertyDescriptors();
for (int i = 0; i < pds.length; i++) {
PropertyDescriptor propertyDescriptor = pds[i];
if (propertyDescriptor.getName().equals("itemQuantities")) {
propertyDescriptor.setValue("transient", Boolean.TRUE);
}
}
BeanToXmlTransient bean = new BeanToXmlTransient();
bean.setId(new Long(1));
bean.setItemName("Item");
bean.setItemColour("Red");
bean.setItemQuantities(new Integer(100));
XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(
"BeanTransient.xml")));
encoder.writeObject(bean);
encoder.close();
}
}
class BeanToXmlTransient {
private Long id;
private String itemName;
private String itemColour;
private Integer itemQuantities;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemColour() {
return itemColour;
}
public void setItemColour(String itemColour) {
this.itemColour = itemColour;
}
public Integer getItemQuantities() {
return itemQuantities;
}
public void setItemQuantities(Integer itemQuantities) {
this.itemQuantities = itemQuantities;
}
}
Preventing a Bean Property from Being Serialized to XML
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
public class Main {
public static void main(String[] argv) throws Exception {
MyClass o = new MyClass();
o.setProp(1);
o.setProps(new int[] { 1, 2, 3 });
XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(
new FileOutputStream("outfilename.xml")));
encoder.writeObject(o);
encoder.close();
}
}
class MyClass {
int i;
public int getProp() {
return i;
}
public void setProp(int i) {
this.i = i;
}
int[] iarray = new int[0];
public int[] getProps() {
return iarray;
}
public void setProps(int[] iarray) {
this.iarray = iarray;
}
static {
try {
BeanInfo info = Introspector.getBeanInfo(MyClass.class);
PropertyDescriptor[] propertyDescriptors = info.getPropertyDescriptors();
for (int i = 0; i < propertyDescriptors.length; ++i) {
PropertyDescriptor pd = propertyDescriptors[i];
if (pd.getName().equals("props")) {
pd.setValue("transient", Boolean.TRUE);
}
}
} catch (IntrospectionException e) {
}
}
}
Process bean properties getter by applying the JavaBean naming conventions.
// $Id: ReflectionHelper.java 16271 2009-04-07 20:20:12Z hardy.ferentschik $
/*
* JBoss, Home of Professional Open Source
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.beans.Introspector;
import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.WildcardType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* Some reflection utility methods.
*
* @author Hardy Ferentschik
*/
public class ReflectionHelper {
/**
* Process bean properties getter by applying the JavaBean naming conventions.
*
* @param member the member for which to get the property name.
*
* @return The bean method name with the "is" or "get" prefix stripped off, <code>null</code>
* the method name id not according to the JavaBeans standard.
*/
public static String getPropertyName(Member member) {
String name = null;
if ( member instanceof Field ) {
name = member.getName();
}
if ( member instanceof Method ) {
String methodName = member.getName();
if ( methodName.startsWith( "is" ) ) {
name = Introspector.decapitalize( methodName.substring( 2 ) );
}
else if ( methodName.startsWith( "get" ) ) {
name = Introspector.decapitalize( methodName.substring( 3 ) );
}
}
return name;
}
}
Read bean"s property value
import java.lang.reflect.InvocationTargetException;
import org.apache.rumons.beanutils.PropertyUtils;
public class Main {
public static void main(String[] args) {
MyClass track = new MyClass();
track.setTitle("this is a test");
String title = (String) PropertyUtils.getSimpleProperty(track, "title");
System.out.println("Title = " + title);
}
}
class MyClass {
private Integer id;
private String title;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
Returns attribute"s setter method. If the method not found then NoSuchMethodException will be thrown.
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/*
* JBoss, Home of Professional Open Source
* Copyright 2005, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This 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 software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
public class Main {
/**
* Returns attribute"s setter method. If the method not found then
* NoSuchMethodException will be thrown.
*
* @param cls
* the class the attribute belongs to
* @param attr
* the attribute"s name
* @param type
* the attribute"s type
* @return attribute"s setter method
* @throws NoSuchMethodException
* if the setter was not found
*/
public final static Method getAttributeSetter(Class cls, String attr, Class type)
throws NoSuchMethodException {
StringBuffer buf = new StringBuffer(attr.length() + 3);
buf.append("set");
if (Character.isLowerCase(attr.charAt(0))) {
buf.append(Character.toUpperCase(attr.charAt(0))).append(attr.substring(1));
} else {
buf.append(attr);
}
return cls.getMethod(buf.toString(), new Class[] { type });
}
}
Serializing a Bean to XML: XMLEncoder only persists the value of public properties.
import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
public class Main {
public static void main(String[] argv) throws Exception {
MyClass o = new MyClass();
o.setProp(1);
o.setProps(new int[] { 1, 2, 3 });
XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(
new FileOutputStream("outfilename.xml")));
encoder.writeObject(o);
encoder.close();
}
}
class MyClass {
// The prop property
int i;
public int getProp() {
return i;
}
public void setProp(int i) {
this.i = i;
}
// The props property
int[] iarray = new int[0];
public int[] getProps() {
return iarray;
}
public void setProps(int[] iarray) {
this.iarray = iarray;
}
}
Serializing an Immutable Bean Property to XML
import java.beans.DefaultPersistenceDelegate;
import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
public class Main {
public static void main(String[] argv) throws Exception {
MyClass o = new MyClass(123);
XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(
new FileOutputStream("outfilename.xml")));
String[] propertyNames = new String[] { "prop" };
encoder.setPersistenceDelegate(MyClass.class,
new DefaultPersistenceDelegate(propertyNames));
encoder.writeObject(o);
encoder.close();
}
}
class MyClass {
int prop;
public MyClass(int prop) {
this.prop = prop;
}
public int getProp() {
return prop;
}
}
Setting an Accessory Component in a JFileChooser Dialog
import java.awt.Dimension;
import java.awt.Graphics;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
public class Main {
public static void main(String[] argv) {
JFileChooser chooser = new JFileChooser();
chooser.setAccessory(new MyAccessory(chooser));
chooser.showOpenDialog(null);
}
}
class MyAccessory extends JComponent implements PropertyChangeListener {
public MyAccessory(JFileChooser chooser) {
chooser.addPropertyChangeListener(this);
setPreferredSize(new Dimension(50, 50));
}
public void propertyChange(PropertyChangeEvent evt) {
if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(evt.getPropertyName())) {
JFileChooser chooser = (JFileChooser) evt.getSource();
// Get the new selected file
File newFile = (File) evt.getNewValue();
repaint();
}
}
public void paint(Graphics g) {
// Paint a preview of the selected file
}
}