updates to Reflection.java
[sbp.git] / src / edu / berkeley / sbp / util / Reflection.java
index 5c13668..5c30d44 100644 (file)
@@ -6,7 +6,7 @@ import java.lang.reflect.*;
 public final class Reflection {
     
     public static Object rebuild(Object o, Class c) {
-        //System.out.println("rebuild " + o + " (a " + (o==null?null:o.getClass().getName()) + ") " + c);
+        System.out.println("rebuild " + o + " (a " + (o==null?null:o.getClass().getName()) + ") " + c);
         if (o==null || c.isAssignableFrom(o.getClass())) return o;
         if ((c == Character.class || c == Character.TYPE) && o instanceof String && ((String)o).length()==1) return new Character(((String)o).charAt(0));
         if (o instanceof Character && c == String.class) return o+"";
@@ -16,7 +16,7 @@ public final class Reflection {
                 Object[] ret = (Object[])Array.newInstance(c.getComponentType(), a.length);
                 for(int i=0; i<ret.length; i++) {
                     Object o2 = rebuild(a[i], c.getComponentType());
-                    //if (o2 != null) System.out.println("storing " + o2.getClass().getName() + " to " + c.getComponentType());
+                    if (o2 != null) System.out.println("storing " + o2.getClass().getName() + " to " + c.getComponentType());
                     ret[i] = o2;
                 }
                 return ret;
@@ -40,6 +40,7 @@ public final class Reflection {
             Object[] ret = (Object[])Array.newInstance(c.getComponentType(), 1);
             ret[0] = o;
             return ret;
+        } else if (c==int.class && o instanceof Number) { return o;
         } else {
             throw new Error("unable to cast " + o + " from " + o.getClass().getName() + " to " + c.getName());
         }
@@ -145,6 +146,10 @@ public final class Reflection {
         if ((c.getModifiers() & Modifier.INTERFACE) != 0) return false;
         return true;
     }
+    public static boolean isStatic(Field f) {
+        if ((f.getModifiers() & Modifier.STATIC) != 0) return true;
+        return false;
+    }
 
     public static Field getField(Class c, String s) {
         try {
@@ -152,6 +157,18 @@ public final class Reflection {
                 if (f.getName().equals(s))
                     return f;
         } catch (Exception e) { }
+        if (c.getSuperclass()==null || c.getSuperclass()==c) return null;
+        return getField(c.getSuperclass(), s);
+    }
+    public static Field getField(Class c, int i) {
+        try {
+            for(Field f : c.getDeclaredFields()) {
+                if (isStatic(f)) continue;
+                return f;
+            }
+            if (c.getSuperclass()==null || c.getSuperclass()==c) return null;
+            return getField(c.getSuperclass(), i);
+        } catch (Exception e) { }
         return null;
     }