property类和listener类,vetoable change event类和listener类在应用程序运行时被bean调用,用于建立用户接口,bean的descriptor 可通过bean-infos和introspection得到,
Basic.java
package chapter1;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
import java.beans.VetoableChangeSupport;
import java.io.Serializable;
public class BasicBean {
boolean property;
int myProperty;
public int getMyProperty()
{
return myProperty;
}
public void setMyProperty(int newValue) throws PropertyVetoException
{try{
int oldValue=myProperty;
myProperty=newValue;
pceListeners.fireVetoableChange("myProperty",new Integer(oldValue),new Integer(newValue));
}catch(PropertyVetoException e){
throw e;
}
}
//Create the listener list
VetoableChangeSupport pceListeners= new VetoableChangeSupport(this);
//The listener wrapper list
public synchronized void addVetoPropertyChangeListener(VetoableChangeListener listener)
{
pceListeners.addVetoableChangeListener(listener);
}
public synchronized void removeVetoPropertyChangeListener(VetoableChangeListener listener)
{
pceListeners.removeVetoableChangeListener(listener);
}
public BasicBean()
{
}
public boolean getProperty()
{
return property;
}
public boolean isProperty()
{
return property;
}
public void setProperty(boolean newValue)
{
property=newValue;
}
}
Instantiate.java
package chapter1;
import java.beans.BeanInfo;
import java.beans.Beans;
import java.beans.Expression;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.beans.Statement;
import java.io.IOException;
public class Instantiate {
public static void main(String[] args)
{ Object o = new MyBean();
try{
Expression expr = new Expression(o,"getProp1",new Object[0]);
expr.execute();
String s =(String)expr.getValue();
Statement stmt = new Statement(o,"setProp1",new Object[]{"new string"});
stmt.execute();
expr = new Expression(o,"getProp2",new Object[0]);
expr.execute();
int i =(Integer)expr.getValue();
stmt = new Statement(o,"setProp2",new Object[]{new Integer(123)});
stmt.execute();
expr = new Expression(o,"getProp3",new Object[0]);
expr.execute();
int i =(Integer)expr.getValue();
stmt = new Statement(o,"setProp3",new Object[]{new byte[]{0x12,0x23}});
stmt.execute();
}catch(Exception e){}
try
{
BasicBean bean = (BasicBean)Beans.instantiate(ClassLoader.getSystemClassLoader(), "MyBeans");
} catch(ClassNotFoundException e){
}catch(IOException e){}
try{
BeanInfo bi = Introspector.getBeanInfo(MyBean.class);
PropertyDescriptor[] pds=bi.getPropertyDescriptors();
for(int i=0;i<pds.length;i++)
{
String propName = pds[i].getName();
}
}
}
}
MyBean.java
package chapter1;
public class MyBean {
String prop1;
int prop2;
public String getProp1(){
return prop1;
}
public void setProp1(String s){
prop1=s;
}
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;
}
}