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 if (c==int.class && o instanceof Number) { return o;
44         } else {
45             throw new Error("unable to cast " + o + " from " + o.getClass().getName() + " to " + c.getName());
46         }
47         return o;
48     }
49
50     public static Object[] newArray(Class c, int i) {
51         return (Object[])Array.newInstance(c, i);
52     }
53
54     public static String indent(String s, int indent) {
55         if (s.indexOf('\n')==-1) return s;
56         StringBuffer ret = new StringBuffer();
57         for(int i=0; i<s.length(); i++) {
58             char c = s.charAt(i);
59             ret.append(c);
60             if (c=='\n')
61                 for(int j=0; j<indent; j++)
62                     ret.append(' ');
63         }
64         return ret.toString();
65     }
66
67     public static String show(Object o) {
68         if (o==null) return "null";
69         if (! (o instanceof Object[])) return o.toString() + " : " + o.getClass().getName();
70         Object[] arr = (Object[])o;
71         StringBuffer ret = new StringBuffer();
72         ret.append(o.getClass().getComponentType().getName());
73         ret.append("["+arr.length+"]:\n");
74         for(int i=0; i<arr.length; i++)
75             ret.append(indent(show(arr[i]), 4) + "\n");
76         return ret.toString();
77     }
78
79     public static Object lub(Object argo) {
80         if (argo instanceof Object[]) return lub((Object[])argo);
81         return argo;
82     }
83     public static Object[] lub(Object[] argo) {
84         if (argo==null) return null;
85         Class c = null;
86         for(int i=0; i<argo.length; i++) {
87             if (argo[i]==null) continue;
88             argo[i] = lub(argo[i]);
89             c = Reflection.lub(c, argo[i].getClass());
90         }
91         if (c==null) c = Object.class;
92         Object[] ret = Reflection.newArray(c, argo.length);
93         System.arraycopy(argo, 0, ret, 0, argo.length);
94         return ret;
95     }
96
97     public static Class lub(Class a, Class b) {
98         if (a==null) return b;
99         if (b==null) return a;
100         if (a==b) return a;
101         if (a.isAssignableFrom(b)) return a;
102         if (b.isAssignableFrom(a)) return b;
103         if (a.isArray() && b.isArray())
104             return arrayClass(lub(a.getComponentType(), b.getComponentType()));
105         return lub(b, a.getSuperclass());
106     }
107
108     public static Class arrayClass(Class c) {
109         return Reflection.newArray(c, 0).getClass();
110     }
111
112     /** a version of <tt>Class.forName</tt> that returns <tt>null</tt> instead of throwing an exception */
113     public static Class forNameOrNull(String s) {
114         try {
115             return Class.forName(s); 
116         } catch (ClassNotFoundException _) {
117             return null;
118         }
119     }
120
121     public static Object fuzzyInvoke(Object o, Member m) { return fuzzyInvoke(o, m, new Object[0]); }
122     /** invoke method/constructor m on object o with arguments args, and perform reasonable coercions as needed */
123     public static Object fuzzyInvoke(Object o, Member m, Object[] args) {
124         try {
125             Class[] argTypes = m instanceof Method ? ((Method)m).getParameterTypes() : ((Constructor)m).getParameterTypes();
126             boolean ok = true;
127             Object[] args2 = new Object[args.length];
128             System.arraycopy(args, 0, args2, 0, args.length);
129             args = args2;
130             for(int i=0; i<args.length; i++) {
131                 Class goal = argTypes[i];
132                 Class actual = args[i] == null ? null : args[i].getClass();
133                 if (args[i] == null || goal.isAssignableFrom(actual)) continue;
134                 try {
135                     args[i] = rebuild(args[i], goal);
136                 } catch (Error e) {
137                     throw new Error(e.getMessage() + "\n   while trying to fuzzyInvoke("+m.getName()+")");
138                 }
139             }
140             // for debugging
141             /*
142             System.out.println("\ninvoking " + o + "." + m);
143             for(int i=0; i<args.length; i++) {
144                 if (args[i] instanceof Object[]) {
145                     System.out.print("  arg => " + zoo(args[i]));
146                 } else {
147                     System.out.println("  arg => " + args[i] + (args[i]==null?"":(" (a " + args[i].getClass().getName() + ")")));
148                 }
149             }
150             */
151             // FIXME: deal with the case where it is an inner class ctor
152             return m instanceof Method ? ((Method)m).invoke(o, args) : ((Constructor)m).newInstance(args);
153         } catch (Exception e) {
154             throw new RuntimeException(e);
155         }
156     }
157
158     private static String zoo(Object o) {
159         if (o==null) return "null";
160         if (o instanceof Object[]) {
161             String ret = "[ ";
162             for(int j=0; j<((Object[])o).length; j++)
163                 ret += zoo(((Object[])o)[j]) + " ";
164             return ret+"]";
165         }
166         return o+"";
167     }
168
169     public static boolean isConcrete(Class c) {
170         if ((c.getModifiers() & Modifier.ABSTRACT) != 0) return false;
171         if ((c.getModifiers() & Modifier.INTERFACE) != 0) return false;
172         return true;
173     }
174     public static boolean isStatic(Field f) {
175         if ((f.getModifiers() & Modifier.STATIC) != 0) return true;
176         return false;
177     }
178
179     public static Field getField(Class c, String s) {
180         try {
181             for(Field f : c.getDeclaredFields())
182                 if (f.getName().equals(s))
183                     return f;
184         } catch (Exception e) { }
185         if (c.getSuperclass()==null || c.getSuperclass()==c) return null;
186         return getField(c.getSuperclass(), s);
187     }
188     public static Field getField(Class c, int i) {
189         try {
190             for(Field f : c.getDeclaredFields()) {
191                 if (isStatic(f)) continue;
192                 return f;
193             }
194             if (c.getSuperclass()==null || c.getSuperclass()==c) return null;
195             return getField(c.getSuperclass(), i);
196         } catch (Exception e) { }
197         return null;
198     }
199
200 }