Java Reference
In-Depth Information
Example 10•1: ShowComponent.java (continued)
public static Vector getComponentsFromArgs(String[] args) {
Vector components = new Vector(); // List of components to return
Component component = null; // The current component
PropertyDescriptor[] properties = null; // Properties of the component
Object[] methodArgs = new Object[1];
// We'll use this below
nextarg: // This is a labeled loop
for(int i = 0; i < args.length; i++) { // Loop through all arguments
// If the argument does not contain an equal sign, then it is
// a component class name. Otherwise it is a property setting
int equalsPos = args[i].indexOf('=');
if (equalsPos == -1) { // Its the name of a component
try {
// Load the named component class
Class componentClass = Class.forName(args[i]);
// Instantiate it to create the component instance
component = (Component)componentClass.newInstance();
// Use JavaBeans to introspect the component
// And get the list of properties it supports
BeanInfo componentBeanInfo =
Introspector.getBeanInfo(componentClass);
properties = componentBeanInfo.getPropertyDescriptors();
}
catch(Exception e) {
// If any step failed, print an error and exit
System.out.println("Can't load, instantiate, " +
"or introspect: " + args[i]);
System.exit(1);
}
// If we succeeded, store the component in the vector
components.addElement(component);
}
else { // The arg is a name=value property specification
String name =args[i].substring(0, equalsPos); // property name
String value =args[i].substring(equalsPos+1); // property value
// If we don't have a component to set this property on, skip!
if (component == null) continue nextarg;
// Now look through the properties descriptors for this
// component to find one with the same name.
for(int p = 0; p < properties.length; p++) {
if (properties[p].getName().equals(name)) {
// Okay, we found a property of the right name.
// Now get its type, and the setter method
Class type = properties[p].getPropertyType();
Method setter = properties[p].getWriteMethod();
// Check if property is read-only!
if (setter == null) {
System.err.println("Property " + name+
" is read-only");
continue nextarg; // continue with next argument
}
// Try to convert the property value to the right type
// We support a small set of common property types here
Search WWH ::




Custom Search