2011-11-26

Minimal JavaBean introspection example

Just playing with JavaBeans, so here's a small example to create a simple JavaBean, set a property and read it.

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;

public class SimpleBean {

  private final String name = "SimpleBean";
  private int size;
  public int getSize() {
    return size;
  }
  public void setSize(int size) {
    this.size = size;
  }
  public String getName() {
    return name;
  }
  
  public static void main(String[] args) throws IntrospectionException {
    SimpleBean sb = new SimpleBean();
    sb.setSize(59);
    BeanInfo bi = Introspector.getBeanInfo(sb.getClass());
    for (PropertyDescriptor pd : bi.getPropertyDescriptors()) {
      testGetValue(sb, pd);
    }
  }
  
  public static void testGetValue(Object sb, PropertyDescriptor pd) {
    System.out.print(pd.getName() + "=");
    Method getter = pd.getReadMethod();
    Object arg1[] = {};
    try {
      Object value = getter.invoke(sb, arg1);
      System.out.println(value);
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      e.printStackTrace();
    }
  }
}

The output of the program is:

class=class SimpleBean
name=SimpleBean
size=59

2011-11-11

Grep -f: No blank lines

If you search for a list of patterns in a data file using grep like below, don't include a blank line in the pattern file otherwise grep prints the entire data file.

grep -f patterns.txt data.txt

It's as if you had typed:

grep "" data.txt

See GNU Grep Manual