You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

419 lines
14 KiB

24 years ago
24 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
  1. /*
  2. +----------------------------------------------------------------------+
  3. | PHP Version 4 |
  4. +----------------------------------------------------------------------+
  5. | Copyright (c) 1997-2002 The PHP Group |
  6. +----------------------------------------------------------------------+
  7. | This source file is subject to version 2.02 of the PHP license, |
  8. | that is bundled with this package in the file LICENSE, and is |
  9. | available at through the world-wide-web at |
  10. | http://www.php.net/license/2_02.txt. |
  11. | If you did not receive a copy of the PHP license and are unable to |
  12. | obtain it through the world-wide-web, please send a note to |
  13. | license@php.net so we can mail you a copy immediately. |
  14. +----------------------------------------------------------------------+
  15. | Author: Sam Ruby (rubys@us.ibm.com) |
  16. +----------------------------------------------------------------------+
  17. */
  18. /* $Id$ */
  19. package net.php;
  20. import java.lang.reflect.*;
  21. import java.util.*;
  22. import java.beans.*;
  23. public class reflect {
  24. static { loadLibrary("reflect"); }
  25. protected static void loadLibrary(String property) {
  26. try {
  27. ResourceBundle bundle = ResourceBundle.getBundle("net.php."+property);
  28. System.loadLibrary(bundle.getString("library"));
  29. } catch (Exception e) {
  30. e.printStackTrace();
  31. }
  32. }
  33. //
  34. // Native methods
  35. //
  36. private static native void setResultFromString(long result, byte value[]);
  37. private static native void setResultFromLong(long result, long value);
  38. private static native void setResultFromDouble(long result, double value);
  39. private static native void setResultFromBoolean(long result, boolean value);
  40. private static native void setResultFromObject(long result, Object value);
  41. private static native void setResultFromArray(long result);
  42. private static native long nextElement(long array);
  43. private static native long hashUpdate(long array, byte key[]);
  44. private static native long hashIndexUpdate(long array, long key);
  45. private static native void setException(long result, byte value[]);
  46. public static native void setEnv();
  47. //
  48. // Helper routines which encapsulate the native methods
  49. //
  50. public static void setResult(long result, Object value) {
  51. if (value == null) return;
  52. if (value instanceof java.lang.String) {
  53. setResultFromString(result, ((String)value).getBytes());
  54. } else if (value instanceof java.lang.Number) {
  55. if (value instanceof java.lang.Integer ||
  56. value instanceof java.lang.Short ||
  57. value instanceof java.lang.Byte) {
  58. setResultFromLong(result, ((Number)value).longValue());
  59. } else {
  60. /* Float, Double, BigDecimal, BigInteger, Double, Long, ... */
  61. setResultFromDouble(result, ((Number)value).doubleValue());
  62. }
  63. } else if (value instanceof java.lang.Boolean) {
  64. setResultFromBoolean(result, ((Boolean)value).booleanValue());
  65. } else if (value.getClass().isArray()) {
  66. long length = Array.getLength(value);
  67. setResultFromArray(result);
  68. for (int i=0; i<length; i++) {
  69. setResult(nextElement(result), Array.get(value, i));
  70. }
  71. } else if (value instanceof java.util.Hashtable) {
  72. Hashtable ht = (Hashtable) value;
  73. setResultFromArray(result);
  74. for (Enumeration e = ht.keys(); e.hasMoreElements(); ) {
  75. Object key = e.nextElement();
  76. long slot;
  77. if (key instanceof Number &&
  78. !(key instanceof Double || key instanceof Float))
  79. slot = hashIndexUpdate(result, ((Number)key).longValue());
  80. else
  81. slot = hashUpdate(result, key.toString().getBytes());
  82. setResult(slot, ht.get(key));
  83. }
  84. } else {
  85. setResultFromObject(result, value);
  86. }
  87. }
  88. Throwable lastException = null;
  89. void lastException(long result) {
  90. setResult(result, lastException);
  91. }
  92. void clearException() {
  93. lastException = null;
  94. }
  95. void setException(long result, Throwable e) {
  96. if (e instanceof InvocationTargetException) {
  97. Throwable t = ((InvocationTargetException)e).getTargetException();
  98. if (t!=null) e=t;
  99. }
  100. lastException = e;
  101. setException(result, e.toString().getBytes());
  102. }
  103. //
  104. // Create an new instance of a given class
  105. //
  106. public void CreateObject(String name, Object args[], long result) {
  107. try {
  108. Vector matches = new Vector();
  109. Constructor cons[] = Class.forName(name).getConstructors();
  110. for (int i=0; i<cons.length; i++) {
  111. if (cons[i].getParameterTypes().length == args.length) {
  112. matches.addElement(cons[i]);
  113. }
  114. }
  115. Constructor selected = (Constructor)select(matches, args);
  116. if (selected == null) {
  117. if (args.length > 0) {
  118. throw new InstantiationException("No matching constructor found");
  119. } else {
  120. // for classes which have no visible constructor, return the class
  121. // useful for classes like java.lang.System and java.util.Calendar.
  122. setResult(result, Class.forName(name));
  123. return;
  124. }
  125. }
  126. Object coercedArgs[] = coerce(selected.getParameterTypes(), args);
  127. setResultFromObject(result, selected.newInstance(coercedArgs));
  128. } catch (Exception e) {
  129. setException(result, e);
  130. }
  131. }
  132. //
  133. // Select the best match from a list of methods
  134. //
  135. private static Object select(Vector methods, Object args[]) {
  136. if (methods.size() == 1) return methods.firstElement();
  137. Object selected = null;
  138. int best = Integer.MAX_VALUE;
  139. for (Enumeration e = methods.elements(); e.hasMoreElements(); ) {
  140. Object element = e.nextElement();
  141. int weight=0;
  142. Class parms[] = (element instanceof Method) ?
  143. ((Method)element).getParameterTypes() :
  144. ((Constructor)element).getParameterTypes();
  145. for (int i=0; i<parms.length; i++) {
  146. if (parms[i].isInstance(args[i])) {
  147. for (Class c=parms[i]; (c=c.getSuperclass()) != null; ) {
  148. if (!c.isInstance(args[i])) break;
  149. weight++;
  150. }
  151. } else if (parms[i].isAssignableFrom(java.lang.String.class)) {
  152. if (!(args[i] instanceof byte[]) && !(args[i] instanceof String))
  153. weight+=9999;
  154. } else if (parms[i].isArray()) {
  155. if (args[i] instanceof java.util.Hashtable)
  156. weight+=256;
  157. else
  158. weight+=9999;
  159. } else if (parms[i].isPrimitive()) {
  160. Class c=parms[i];
  161. if (args[i] instanceof Number) {
  162. if (c==Boolean.TYPE) weight+=5;
  163. if (c==Character.TYPE) weight+=4;
  164. if (c==Byte.TYPE) weight+=3;
  165. if (c==Short.TYPE) weight+=2;
  166. if (c==Integer.TYPE) weight++;
  167. if (c==Float.TYPE) weight++;
  168. } else if (args[i] instanceof Boolean) {
  169. if (c!=Boolean.TYPE) weight+=9999;
  170. } else if (args[i] instanceof String) {
  171. if (c== Character.TYPE || ((String)args[i]).length()>0)
  172. weight+=((String)args[i]).length();
  173. else
  174. weight+=64;
  175. } else {
  176. weight+=9999;
  177. }
  178. } else {
  179. weight+=9999;
  180. }
  181. }
  182. if (weight < best) {
  183. if (weight == 0) return element;
  184. best = weight;
  185. selected = element;
  186. }
  187. }
  188. return selected;
  189. }
  190. //
  191. // Coerce arguments when possible to conform to the argument list.
  192. // Java's reflection will automatically do widening conversions,
  193. // unfortunately PHP only supports wide formats, so to be practical
  194. // some (possibly lossy) conversions are required.
  195. //
  196. private static Object[] coerce(Class parms[], Object args[]) {
  197. Object result[] = args;
  198. for (int i=0; i<args.length; i++) {
  199. if (args[i] instanceof byte[] && !parms[i].isArray()) {
  200. Class c = parms[i];
  201. String s = new String((byte[])args[i]);
  202. result[i] = s;
  203. try {
  204. if (c == Boolean.TYPE) result[i]=new Boolean(s);
  205. if (c == Byte.TYPE) result[i]=new Byte(s);
  206. if (c == Short.TYPE) result[i]=new Short(s);
  207. if (c == Integer.TYPE) result[i]=new Integer(s);
  208. if (c == Float.TYPE) result[i]=new Float(s);
  209. if (c == Long.TYPE) result[i]=new Long(s);
  210. if (c == Character.TYPE && s.length()>0)
  211. result[i]=new Character(s.charAt(0));
  212. } catch (NumberFormatException n) {
  213. // oh well, we tried!
  214. }
  215. } else if (args[i] instanceof Number && parms[i].isPrimitive()) {
  216. if (result==args) result=(Object[])result.clone();
  217. Class c = parms[i];
  218. Number n = (Number)args[i];
  219. if (c == Boolean.TYPE) result[i]=new Boolean(0.0!=n.floatValue());
  220. if (c == Byte.TYPE) result[i]=new Byte(n.byteValue());
  221. if (c == Short.TYPE) result[i]=new Short(n.shortValue());
  222. if (c == Integer.TYPE) result[i]=new Integer(n.intValue());
  223. if (c == Float.TYPE) result[i]=new Float(n.floatValue());
  224. if (c == Long.TYPE && !(n instanceof Long))
  225. result[i]=new Long(n.longValue());
  226. } else if (args[i] instanceof Hashtable && parms[i].isArray()) {
  227. try {
  228. Hashtable ht = (Hashtable)args[i];
  229. int size = ht.size();
  230. // Verify that the keys are Long, and determine maximum
  231. for (Enumeration e = ht.keys(); e.hasMoreElements(); ) {
  232. int index = ((Long)e.nextElement()).intValue();
  233. if (index >= size) size = index+1;
  234. }
  235. Object tempArray[] = new Object[size];
  236. Class tempTarget[] = new Class[size];
  237. Class targetType = parms[i].getComponentType();
  238. // flatten the hash table into an array
  239. for (int j=0; j<size; j++) {
  240. tempArray[j] = ht.get(new Long(j));
  241. if (tempArray[j] == null && targetType.isPrimitive())
  242. throw new Exception("bail");
  243. tempTarget[j] = targetType;
  244. }
  245. // coerce individual elements into the target type
  246. Object coercedArray[] = coerce(tempTarget, tempArray);
  247. // copy the results into the desired array type
  248. Object array = Array.newInstance(targetType,size);
  249. for (int j=0; j<size; j++) {
  250. Array.set(array, j, coercedArray[j]);
  251. }
  252. result[i]=array;
  253. } catch (Exception e) {
  254. // leave result[i] alone...
  255. }
  256. }
  257. }
  258. return result;
  259. }
  260. //
  261. // Invoke a method on a given object
  262. //
  263. public void Invoke
  264. (Object object, String method, Object args[], long result)
  265. {
  266. try {
  267. Vector matches = new Vector();
  268. // gather
  269. for (Class jclass = object.getClass();;jclass=(Class)object) {
  270. while (!Modifier.isPublic(jclass.getModifiers())) {
  271. // OK, some joker gave us an instance of a non-public class
  272. // This often occurs in the case of enumerators
  273. // Substitute the first public interface in its place,
  274. // and barring that, try the superclass
  275. Class interfaces[] = jclass.getInterfaces();
  276. jclass=jclass.getSuperclass();
  277. for (int i=interfaces.length; i-->0;) {
  278. if (Modifier.isPublic(interfaces[i].getModifiers())) {
  279. jclass=interfaces[i];
  280. }
  281. }
  282. }
  283. Method methods[] = jclass.getMethods();
  284. for (int i=0; i<methods.length; i++) {
  285. if (methods[i].getName().equalsIgnoreCase(method) &&
  286. methods[i].getParameterTypes().length == args.length) {
  287. matches.addElement(methods[i]);
  288. }
  289. }
  290. // try a second time with the object itself, if it is of type Class
  291. if (!(object instanceof Class) || (jclass==object)) break;
  292. }
  293. Method selected = (Method)select(matches, args);
  294. if (selected == null) throw new NoSuchMethodException(method);
  295. Object coercedArgs[] = coerce(selected.getParameterTypes(), args);
  296. setResult(result, selected.invoke(object, coercedArgs));
  297. } catch (Exception e) {
  298. setException(result, e);
  299. }
  300. }
  301. //
  302. // Get or Set a property
  303. //
  304. public void GetSetProp
  305. (Object object, String prop, Object args[], long result)
  306. {
  307. try {
  308. for (Class jclass = object.getClass();;jclass=(Class)object) {
  309. while (!Modifier.isPublic(jclass.getModifiers())) {
  310. // OK, some joker gave us an instance of a non-public class
  311. // Substitute the first public interface in its place,
  312. // and barring that, try the superclass
  313. Class interfaces[] = jclass.getInterfaces();
  314. jclass=jclass.getSuperclass();
  315. for (int i=interfaces.length; i-->0;) {
  316. if (Modifier.isPublic(interfaces[i].getModifiers())) {
  317. jclass=interfaces[i];
  318. }
  319. }
  320. }
  321. BeanInfo beanInfo = Introspector.getBeanInfo(jclass);
  322. PropertyDescriptor props[] = beanInfo.getPropertyDescriptors();
  323. for (int i=0; i<props.length; i++) {
  324. if (props[i].getName().equalsIgnoreCase(prop)) {
  325. Method method;
  326. if (args!=null && args.length>0) {
  327. method=props[i].getWriteMethod();
  328. args = coerce(method.getParameterTypes(), args);
  329. } else {
  330. method=props[i].getReadMethod();
  331. }
  332. setResult(result, method.invoke(object, args));
  333. return;
  334. }
  335. }
  336. Field jfields[] = jclass.getFields();
  337. for (int i=0; i<jfields.length; i++) {
  338. if (jfields[i].getName().equalsIgnoreCase(prop)) {
  339. if (args!=null && args.length>0) {
  340. args = coerce(new Class[] {jfields[i].getType()}, args);
  341. jfields[i].set(object, args[0]);
  342. } else {
  343. setResult(result, jfields[i].get(object));
  344. }
  345. return;
  346. }
  347. }
  348. // try a second time with the object itself, if it is of type Class
  349. if (!(object instanceof Class) || (jclass==object)) break;
  350. }
  351. } catch (Exception e) {
  352. setException(result, e);
  353. }
  354. }
  355. //
  356. // Helper routines for the C implementation
  357. //
  358. public Object MakeArg(boolean b) { return new Boolean(b); }
  359. public Object MakeArg(long l) { return new Long(l); }
  360. public Object MakeArg(double d) { return new Double(d); }
  361. }