26 November 2011

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();
    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);
    } catch (IllegalArgumentException e) {
    } catch (IllegalAccessException e) {
    } catch (InvocationTargetException e) {

The output of the program is:

class=class SimpleBean

11 November 2011

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