checkpoint
[sbp.git] / src / edu / berkeley / sbp / util / Reflection.java
1 package edu.berkeley.sbp.util;
2 import java.io.*;
3 import java.lang.reflect.*;
4
5 /** Random reflection-related utilities */
6 public final class Reflection {
7     
8     public static Object rebuild(Object o, Class c) {
9         //System.out.println("rebuild " + o + " (a " + (o==null?null:o.getClass().getName()) + ") " + c);
10         if (o==null || c.isAssignableFrom(o.getClass())) return o;
11         if ((c == Character.class || c == Character.TYPE) && o instanceof String && ((String)o).length()==1) return new Character(((String)o).charAt(0));
12         if (o instanceof Character && c == String.class) return o+"";
13         if (o instanceof Object[]) {
14             Object[] a = (Object[])o;
15             if (c.isArray()) {
16                 Object[] ret = (Object[])Array.newInstance(c.getComponentType(), a.length);
17                 for(int i=0; i<ret.length; i++) {
18                     Object o2 = rebuild(a[i], c.getComponentType());
19                     //if (o2 != null) System.out.println("storing " + o2.getClass().getName() + " to " + c.getComponentType());
20                     ret[i] = o2;
21                 }
22                 return ret;
23             }
24             if (c == String.class) {
25                 boolean ok = true;
26                 for(int i=0; i<a.length; i++)
27                     if (a[i]==null || (!(a[i] instanceof Character) && !(a[i] instanceof String)))
28                         ok = false;
29                 if (ok) {
30                     StringBuffer s = new StringBuffer();
31                     for(int i=0; i<a.length; i++)
32                         s.append(a[i] instanceof Character
33                                  ? (((Character)a[i]).charValue())+""
34                                  : (String)a[i]
35                                  );
36                     return s.toString();
37                 }
38             }
39         } else if (c.isArray()) {
40             Object[] ret = (Object[])Array.newInstance(c.getComponentType(), 1);
41             ret[0] = o;
42             return ret;
43         } else {
44             throw new Error("unable to cast " + o + " from " + o.getClass().getName() + " to " + c.getName());
45         }
46         return o;
47     }
48
49     public static Object[] newArray(Class c, int i) {
50         return (Object[])Array.newInstance(c, i);
51     }
52
53     public static Object lub(Object argo) {
54         if (argo instanceof Object[]) return lub((Object[])argo);
55         return argo;
56     }
57     public static Object[] lub(Object[] argo) {
58         if (argo==null) return null;
59         Class c = null;
60         for(int i=0; i<argo.length; i++) {
61             if (argo[i]==null) continue;
62             argo[i] = lub(argo[i]);
63             c = Reflection.lub(c, argo[i].getClass());
64         }
65         if (c==null) c = Object.class;
66         Object[] ret = Reflection.newArray(c, argo.length);
67         System.arraycopy(argo, 0, ret, 0, argo.length);
68         return ret;
69     }
70
71     public static Class lub(Class a, Class b) {
72         if (a==null) return b;
73         if (b==null) return a;
74         if (a==b) return a;
75         if (a.isAssignableFrom(b)) return a;
76         if (b.isAssignableFrom(a)) return b;
77         if (a.isArray() && b.isArray())
78             return arrayClass(lub(a.getComponentType(), b.getComponentType()));
79         return lub(b, a.getSuperclass());
80     }
81
82     public static Class arrayClass(Class c) {
83         return Reflection.newArray(c, 0).getClass();
84     }
85
86     /** a version of <tt>Class.forName</tt> that returns <tt>null</tt> instead of throwing an exception */
87     public static Class forNameOrNull(String s) {
88         try {
89             return Class.forName(s); 
90         } catch (ClassNotFoundException _) {
91             return null;
92         }
93     }
94
95     public static Object fuzzyInvoke(Object o, Member m) { return fuzzyInvoke(o, m, new Object[0]); }
96     /** invoke method/constructor m on object o with arguments args, and perform reasonable coercions as needed */
97     public static Object fuzzyInvoke(Object o, Member m, Object[] args) {
98         try {
99             Class[] argTypes = m instanceof Method ? ((Method)m).getParameterTypes() : ((Constructor)m).getParameterTypes();
100             boolean ok = true;
101             Object[] args2 = new Object[args.length];
102             System.arraycopy(args, 0, args2, 0, args.length);
103             args = args2;
104             for(int i=0; i<args.length; i++) {
105                 Class goal = argTypes[i];
106                 Class actual = args[i] == null ? null : args[i].getClass();
107                 if (args[i] == null || goal.isAssignableFrom(actual)) continue;
108                 try {
109                     args[i] = rebuild(args[i], goal);
110                 } catch (Error e) {
111                     throw new Error(e.getMessage() + "\n   while trying to fuzzyInvoke("+m.getName()+")");
112                 }
113             }
114             // for debugging
115             /*
116             System.out.println("\ninvoking " + o + "." + m);
117             for(int i=0; i<args.length; i++) {
118                 if (args[i] instanceof Object[]) {
119                     System.out.print("  arg => " + zoo(args[i]));
120                 } else {
121                     System.out.println("  arg => " + args[i] + (args[i]==null?"":(" (a " + args[i].getClass().getName() + ")")));
122                 }
123             }
124             */
125             // FIXME: deal with the case where it is an inner class ctor
126             return m instanceof Method ? ((Method)m).invoke(o, args) : ((Constructor)m).newInstance(args);
127         } catch (Exception e) {
128             throw new RuntimeException(e);
129         }
130     }
131
132     private static String zoo(Object o) {
133         if (o==null) return "null";
134         if (o instanceof Object[]) {
135             String ret = "[ ";
136             for(int j=0; j<((Object[])o).length; j++)
137                 ret += zoo(((Object[])o)[j]) + " ";
138             return ret+"]";
139         }
140         return o+"";
141     }
142
143     public static boolean isConcrete(Class c) {
144         if ((c.getModifiers() & Modifier.ABSTRACT) != 0) return false;
145         if ((c.getModifiers() & Modifier.INTERFACE) != 0) return false;
146         return true;
147     }
148
149     public static Field getField(Class c, String s) {
150         try {
151             for(Field f : c.getDeclaredFields())
152                 if (f.getName().equals(s))
153                     return f;
154         } catch (Exception e) { }
155         return null;
156     }
157
158 }