예제 #1
0
 public static Object parseWithIntrospection(
     String elementName, Class objectClass, XmlPullParser parser) throws Exception {
   boolean done = false;
   Object object = objectClass.newInstance();
   while (!done) {
     int eventType = parser.next();
     if (eventType == XmlPullParser.START_TAG) {
       String name = parser.getName();
       String stringValue = parser.nextText();
       PropertyDescriptor descriptor = new PropertyDescriptor(name, objectClass);
       // Load the class type of the property.
       Class propertyType = descriptor.getPropertyType();
       // Get the value of the property by converting it from a
       // String to the correct object type.
       Object value = decode(propertyType, stringValue);
       // Set the value of the bean.
       descriptor.getWriteMethod().invoke(object, value);
     } else if (eventType == XmlPullParser.END_TAG) {
       if (parser.getName().equals(elementName)) {
         done = true;
       }
     }
   }
   return object;
 }
예제 #2
0
 /**
  * Decodes a String into an object of the specified type. If the object type is not supported,
  * null will be returned.
  *
  * @param type the type of the property.
  * @param value the encode String value to decode.
  * @return the String value decoded into the specified type.
  * @throws Exception If decoding failed due to an error.
  */
 private static Object decode(Class type, String value) throws Exception {
   if (type.getName().equals("java.lang.String")) {
     return value;
   }
   if (type.getName().equals("boolean")) {
     return Boolean.valueOf(value);
   }
   if (type.getName().equals("int")) {
     return Integer.valueOf(value);
   }
   if (type.getName().equals("long")) {
     return Long.valueOf(value);
   }
   if (type.getName().equals("float")) {
     return Float.valueOf(value);
   }
   if (type.getName().equals("double")) {
     return Double.valueOf(value);
   }
   if (type.getName().equals("java.lang.Class")) {
     return Class.forName(value);
   }
   return null;
 }