[ Back | Previous | Next ]

How to translate ResultSets to Objects with reflection?

Package:
java.lang.reflect.*
Product:
JDK
Release:
1.1
Related Links:
General
Field
Method
Comment:
Calling 
	ScratchBook.transformResult(this, res);

////////

/**
 * Insert the method's description here.
 * Creation date: (5/11/01 9:17:48 PM)
 * @return java.lang.Object
 * @param ref java.lang.Object
 * @param res java.sql.ResultSet
 */
public static Object transformResult(Object ref, java.sql.ResultSet res)
{
	try
	{
		int col = res.getMetaData().getColumnCount();
		String colName = null;
		for (int i = 1; i <= col; i++)
		{
			colName = res.getMetaData().getColumnName(i);
			try
			{
				java.lang.reflect.Field f = ref.getClass().getDeclaredField(colName.toLowerCase());
				if (f != null)
				{
					if (f.getType() == java.sql.Date.class)
					{
						f.set(ref, res.getDate(colName));
					}
					else
						if (f.getType() == int.class)
						{
							f.setInt(ref, res.getInt(colName));
						}
						else
						{
							f.set(ref, res.getString(colName));
						}
				}
			}
			catch (NoSuchFieldException nfe)
			{
				akaan.util.Debug.printDebugMessage("ScratchBook.transformResult", "skipping " + colName);
			}
			catch (IllegalArgumentException il)
			{
				akaan.util.Debug.printDebugMessage("ScratchBook.transformResult", "illegal value for " + colName);
			}
		}
	}
	catch (Throwable t)
	{
		akaan.util.Debug.printThrowable("ScratchBook.transformResult", t);
	}
	return null;
}
1