9-Jul-05 (Created: 9-Jul-05) | More in 'CS-Java'

java/samplecode/reflection

FieldInfo

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class FieldInfo 
{
	//For clarity of code I am not generating the getters and setters
	//Generate them before production
	public Method m_getAccessor = null;
	public Method m_setAccessor = null;
	public String m_name = null;
	public String m_xmlName = null;
	public boolean m_attribute = false;
	private Class m_class = null;
	private Class m_fieldType = null;
	
	public FieldInfo(Class fieldClass, String name, String xmlName, boolean isAttribute)
		throws NoSuchMethodException, NoSuchFieldException
	{
		m_name = name;
		m_xmlName = xmlName;
		m_attribute = isAttribute;
		m_class = fieldClass;
		m_fieldType = getFieldType(name);
		m_getAccessor = getAccessorGetMethod(name);
		m_setAccessor = getAccessorSetMethod(name);
	}
	
	
	public FieldInfo(Class fieldClass,String name, String xmlName) 
	throws NoSuchMethodException, NoSuchFieldException
	{
		this(fieldClass,name,xmlName,false);
	}
	
	public FieldInfo(Class fieldClass, String name) 
	throws NoSuchMethodException, NoSuchFieldException
	{
		this(fieldClass,name,name,false);
	}
	
	String getValueAsString(Object o)
	throws InvocationTargetException, IllegalAccessException
	{
		Object reply = m_getAccessor.invoke(o,null);
		return reply.toString();
	}
	
	private Method getAccessorGetMethod(String fieldName)
		throws NoSuchMethodException
	{
		String firstPart = fieldName.substring(0,1);
		String secondPart = fieldName.substring(1);
		String getMethodName = "get" + firstPart.toUpperCase() + secondPart;
		//System.out.println(getMethodName);
		return m_class.getDeclaredMethod(getMethodName,null);
	}
	
	private Method getAccessorSetMethod(String fieldName)
	throws NoSuchMethodException
	{
		String firstPart = fieldName.substring(0,1);
		String secondPart = fieldName.substring(1);
		String getMethodName = "set" + firstPart.toUpperCase() + secondPart;
		//System.out.println(getMethodName);
		Class parameters[] = new Class[1];
		parameters[0] = this.m_fieldType;
		
		return m_class.getDeclaredMethod(getMethodName,parameters);
	}
	
	private Class getFieldType(String fieldName)
		throws NoSuchFieldException
	{
		Field field = m_class.getDeclaredField(fieldName);
		Class fieldClass = field.getType();
		return fieldClass;
	}
	
	private String getTypeName(String fieldName)
	{
		return this.m_fieldType.getName();
	}
	
	public void setValueUsingString(Object o, String fieldValue)
	throws InvocationTargetException, IllegalAccessException
	{
		Object parameter = ReflectionUtils.getStringAsObject(m_fieldType.getName(),fieldValue);
		Object paramArray[] = new Object[1];
		paramArray[0] = parameter;
		Object reply = m_setAccessor.invoke(o,paramArray);
	}
}

BeanInfo

public class BeanInfo 
{
   private Class m_class;

   private List m_fieldList = new ArrayList();
   private List m_FieldInfoList = new ArrayList();
   private Map  m_FieldInfoMap = new HashMap();
   
   private static boolean xmlMapInitialized = false;
   private static Map m_xmlNameMap = new HashMap();
   
   private String xmlNodeName = null;
   
   /**
    * @return Returns the xmlNodeName.
    */
   public String getXmlNodeName() {
      return xmlNodeName;
   }
   /**
    * @param xmlNodeName The xmlNodeName to set.
    */
   public void setXmlNodeName(String xmlNodeName) {
      this.xmlNodeName = xmlNodeName;
   }
   public BeanInfo(Object bean) 
   throws NoSuchMethodException, NoSuchFieldException
   {
      this(bean.getClass());
   }
   
   public BeanInfo(Class inClass) 
      throws NoSuchMethodException, NoSuchFieldException
   {
      m_class = inClass;
      Field fieldArray[] = m_class.getDeclaredFields();
      for(int i=0;i<fieldArray.length;i++)
      {
         Field thisField = fieldArray[i];
         String fieldName = thisField.getName();
         if (isStatic(thisField))
         {
            //static field
            //Go on to the next field
            continue;
         }
         registerField(fieldName);
      }
      xmlNodeName = m_class.getName();
   }
   
   public Iterator getFieldNames()
   {
      return m_fieldList.iterator();
   }
   
   public Iterator getFieldInfos()
   {
      return m_FieldInfoList.iterator();
   }
   
   private void registerField(String fieldName)
      throws NoSuchMethodException, NoSuchFieldException
   {
      m_fieldList.add(fieldName);
      FieldInfo fi = new FieldInfo(m_class,fieldName);
      this.m_FieldInfoMap.put(fieldName, fi);
      m_FieldInfoList.add(fi);
   }
   
   public String getValueAsString(String fieldName, Object o)
      throws InvocationTargetException, IllegalAccessException
   {
      FieldInfo fi = (FieldInfo)m_FieldInfoMap.get(fieldName);
      return fi.getValueAsString(o);
      
   }
   public void registerMapping(String fieldName, String xmlName)
   {
      registerMapping(fieldName, xmlName, false);
   }
   
   public void registerMapping(String fieldName, String xmlName, 
                                  boolean isAttribute)
   {
      FieldInfo fi = (FieldInfo)m_FieldInfoMap.get(fieldName);
      if (fi == null)
      {
         throw new RuntimeException(
		    "No field information found for field:" + fieldName);
      }
      fi.m_xmlName=xmlName;
      fi.m_attribute = isAttribute;
   }
   
   public void unRegisterMapping(String fieldName)
   {
      FieldInfo fi = (FieldInfo)m_FieldInfoMap.get(fieldName);
      if (fi == null)
      {
         throw new RuntimeException(
		          "No field information found for field:" + fieldName);
      }
      m_FieldInfoMap.remove(fi);
   }
   
   public FieldInfo getFieldInfo(String xmlName)
   {
      initializeXmlMap();
      FieldInfo fi = (FieldInfo)m_xmlNameMap.get(xmlName);
      return fi;
   }
   
   private void initializeXmlMap()
   {
      if (xmlMapInitialized == true) return;
      
      Iterator fieldInfos = getFieldInfos();
      while(fieldInfos.hasNext())
      {
         FieldInfo fi = (FieldInfo)fieldInfos.next();
         String xmlName = fi.m_xmlName;
         m_xmlNameMap.put(xmlName,fi);
      }
   }
   
   public String convertToString(Object o)
   {
      //Make sure the types are right 
      String myClassName = m_class.getName();
      String inClassName = o.getClass().getName();
      if (!(myClassName.equals(inClassName)))
      {
         throw new RuntimeException(
		        "Unexpected classname. Expecting " 
				+ myClassName 
				+ " but got " 
				+ inClassName);
      }
      
      //Get a buffer
      StringBuffer sbuf = new StringBuffer();
      
      //Print the header
      
      //good to go
      //Get all public fields
      Iterator fieldInfos = this.getFieldInfos();
      while(fieldInfos.hasNext())
      {
         FieldInfo fi = (FieldInfo)fieldInfos.next();
         String fieldName = fi.m_name;
         String fieldXmlName = fi.m_xmlName;
         String value = "";
         try
         {
            value = fi.getValueAsString(o);
         }
         catch(Exception x)
         {
            x.printStackTrace();
            value="Exception. The message is:" + x.getMessage();
         }
         sbuf.append("\n" + fieldName + "='" + value + "'");
      }
      return sbuf.toString();
   }
   
   public void optimize()
   {
      initializeXmlMap();
   }
   private boolean isStatic(Field field)
   {
      int modifier = field.getModifiers();
      return Modifier.isStatic(modifier);
   }
}//eof-class

ReflectionUtils

public class ReflectionUtils 
{
   
   //This can be further optimized using functors
   //For now this will do
   public static Object getStringAsObject(String typeName, String value)
   {
      if (typeName.equals("java.lang.String"))
      {
         return value;
      }
      if (typeName.equals("int"))
      {
         return getStringAsInteger(value);
      }
      
      if (typeName.equals("java.util.Calendar"))
      {
         return getStringAsCalendar(value);
      }
      
      if (typeName.equals("long"))
      {
         return getStringAsLong(value);
      }
      if (typeName.equals("double"))
      {
         return getStringAsDouble(value);
      }
      if (typeName.equals("float"))
      {
         return getStringAsFloat(value);
      }
      throw new RuntimeException("Unrecognized type encountered:" 
	             + typeName);
   }
   
   public static Integer getStringAsInteger(String value)
   {
      return new Integer(Integer.parseInt(value));
   }

   public static Long getStringAsLong(String value)
   {
      return new Long(Long.parseLong(value));
   }
   
   public static Double getStringAsDouble(String value)
   {
      return new Double(Double.parseDouble(value));
   }
   
   public static Float getStringAsFloat(String value)
   {
      return new Float(Float.parseFloat(value));
   }
   
   public static Calendar getStringAsCalendar(String value)
   {
      try
      {
         Calendar cal = Calendar.getInstance();
         cal.setTime(ReflectionUtils.someDateTimeFormatter.parse(value));
         return cal;
      }
      catch(ParseException x)
      {
         RuntimeException rt = 
            new RuntimeException("Could not parse a timestamp:" + value, x);
         throw rt;
      }
   }
   
   public static String getValueAsString(Object o)
   {
      if (o instanceof Calendar)
      {
         //do this
         Calendar cal = (Calendar)o;
         //format the date and return
      }
      return o.toString();
   }
}//eof-class