/interpreter/tags/at_build150307/src/edu/vub/at/objects/symbiosis/JavaClass.java

http://ambienttalk.googlecode.com/ · Java · 418 lines · 220 code · 38 blank · 160 comment · 23 complexity · b4790d6ffedd3a29745aa79fc0becca9 MD5 · raw file

  1. /**
  2. * AmbientTalk/2 Project
  3. * JavaClass.java created on 3-nov-2006 at 10:54:38
  4. * (c) Programming Technology Lab, 2006 - 2007
  5. * Authors: Tom Van Cutsem & Stijn Mostinckx
  6. *
  7. * Permission is hereby granted, free of charge, to any person
  8. * obtaining a copy of this software and associated documentation
  9. * files (the "Software"), to deal in the Software without
  10. * restriction, including without limitation the rights to use,
  11. * copy, modify, merge, publish, distribute, sublicense, and/or
  12. * sell copies of the Software, and to permit persons to whom the
  13. * Software is furnished to do so, subject to the following
  14. * conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be
  17. * included in all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  20. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  21. * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  22. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  23. * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  24. * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  25. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  26. * OTHER DEALINGS IN THE SOFTWARE.
  27. */
  28. package edu.vub.at.objects.symbiosis;
  29. import edu.vub.at.actors.net.Logging;
  30. import edu.vub.at.exceptions.InterpreterException;
  31. import edu.vub.at.exceptions.XArityMismatch;
  32. import edu.vub.at.exceptions.XDuplicateSlot;
  33. import edu.vub.at.exceptions.XSelectorNotFound;
  34. import edu.vub.at.exceptions.XTypeMismatch;
  35. import edu.vub.at.exceptions.XUnassignableField;
  36. import edu.vub.at.exceptions.XUndefinedField;
  37. import edu.vub.at.objects.ATBoolean;
  38. import edu.vub.at.objects.ATContext;
  39. import edu.vub.at.objects.ATField;
  40. import edu.vub.at.objects.ATMethod;
  41. import edu.vub.at.objects.ATNil;
  42. import edu.vub.at.objects.ATObject;
  43. import edu.vub.at.objects.ATStripe;
  44. import edu.vub.at.objects.ATTable;
  45. import edu.vub.at.objects.coercion.NativeStripes;
  46. import edu.vub.at.objects.grammar.ATSymbol;
  47. import edu.vub.at.objects.mirrors.PrimitiveMethod;
  48. import edu.vub.at.objects.mirrors.Reflection;
  49. import edu.vub.at.objects.natives.NATBoolean;
  50. import edu.vub.at.objects.natives.NATNil;
  51. import edu.vub.at.objects.natives.NATNumber;
  52. import edu.vub.at.objects.natives.NATObject;
  53. import edu.vub.at.objects.natives.NATTable;
  54. import edu.vub.at.objects.natives.NATText;
  55. import edu.vub.at.objects.natives.grammar.AGSymbol;
  56. import java.lang.ref.SoftReference;
  57. import java.util.HashMap;
  58. /**
  59. * A JavaClass instance represents a Java Class under symbiosis.
  60. *
  61. * Java classes are treated as AmbientTalk 'singleton' objects:
  62. *
  63. * - cloning a Java class results in the same Java class instance
  64. * - sending 'new' to a Java class invokes the constructor and returns a new instance of the class under symbiosis
  65. * - all static fields and methods of the Java class are reflected under symbiosis as fields and methods of the AT object
  66. *
  67. * A Java Class object that represents an interface can furthermore be used
  68. * as an AmbientTalk stripe. The stripe's name corresponds to the interface's full name.
  69. *
  70. * JavaClass instances are pooled (on a per-actor basis): there should exist only one JavaClass instance
  71. * for each Java class loaded into the JVM. Because the JVM ensures that a Java class
  72. * can only be loaded once, we can use the Java class wrapped by the JavaClass instance
  73. * as a unique key to identify its corresponding JavaClass instance.
  74. *
  75. * @author tvcutsem
  76. */
  77. public final class JavaClass extends NATObject implements ATStripe {
  78. /**
  79. * A thread-local hashmap pooling all of the JavaClass wrappers for
  80. * the current actor, referring to them using SOFT references, such
  81. * that unused wrappers can be GC-ed when running low on memory.
  82. */
  83. private static final ThreadLocal _JAVACLASS_POOL_ = new ThreadLocal() {
  84. protected synchronized Object initialValue() {
  85. return new HashMap();
  86. }
  87. };
  88. public static final JavaClass wrapperFor(Class c) {
  89. HashMap map = (HashMap) _JAVACLASS_POOL_.get();
  90. if (map.containsKey(c)) {
  91. SoftReference ref = (SoftReference) map.get(c);
  92. JavaClass cls = (JavaClass) ref.get();
  93. if (cls != null) {
  94. return cls;
  95. } else {
  96. map.remove(c);
  97. cls = new JavaClass(c);
  98. map.put(c, new SoftReference(cls));
  99. return cls;
  100. }
  101. } else {
  102. JavaClass jc = new JavaClass(c);
  103. map.put(c, new SoftReference(jc));
  104. return jc;
  105. }
  106. }
  107. // primitive fields and method of a JavaClass wrapper
  108. private static final AGSymbol _PST_NAME_ = AGSymbol.jAlloc("parentStripes");
  109. private static final AGSymbol _SNM_NAME_ = AGSymbol.jAlloc("stripeName");
  110. /** def isSubstripeOf(stripe) { nil } */
  111. private static final PrimitiveMethod _PRIM_SST_ = new PrimitiveMethod(
  112. AGSymbol.jAlloc("isSubstripeOf"), NATTable.atValue(new ATObject[] { AGSymbol.jAlloc("stripe")})) {
  113. public ATObject base_apply(ATTable arguments, ATContext ctx) throws InterpreterException {
  114. if (!arguments.base_getLength().equals(NATNumber.ONE)) {
  115. throw new XArityMismatch("isSubstripeOf", 1, arguments.base_getLength().asNativeNumber().javaValue);
  116. }
  117. return ctx.base_getLexicalScope().asJavaClassUnderSymbiosis().base_isSubstripeOf(arguments.base_at(NATNumber.ONE).asStripe());
  118. }
  119. };
  120. private final Class wrappedClass_;
  121. /**
  122. * A JavaClass wrapping a class c is an object that has the lexical scope as its lexical parent
  123. * and has NIL as its dynamic parent.
  124. *
  125. * If the JavaClass wraps a Java interface type, JavaClass instances are
  126. * also stripes.
  127. */
  128. private JavaClass(Class wrappedClass) {
  129. super(wrappedClass.isInterface() ?
  130. new ATStripe[] { NativeStripes._STRIPE_ } :
  131. NATObject._NO_STRIPES_);
  132. wrappedClass_ = wrappedClass;
  133. // add the two fields and one method needed for an ATStripe
  134. if (wrappedClass.isInterface()) {
  135. Class[] extendedInterfaces = wrappedClass_.getInterfaces();
  136. ATObject[] stripes = new ATObject[extendedInterfaces.length];
  137. for (int i = 0; i < extendedInterfaces.length; i++) {
  138. stripes[i] = JavaClass.wrapperFor(extendedInterfaces[i]);
  139. }
  140. try {
  141. super.meta_defineField(_PST_NAME_, NATTable.atValue(stripes));
  142. super.meta_defineField(_SNM_NAME_, AGSymbol.jAlloc(wrappedClass_.getName()));
  143. super.meta_addMethod(_PRIM_SST_);
  144. } catch (InterpreterException e) {
  145. Logging.Actor_LOG.fatal("Error while initializing Java Class as stripe: " + wrappedClass.getName(), e);
  146. }
  147. }
  148. }
  149. public Class getWrappedClass() { return wrappedClass_; }
  150. public JavaClass asJavaClassUnderSymbiosis() throws XTypeMismatch { return this; }
  151. public boolean equals(Object other) {
  152. return ((other instanceof JavaClass) &&
  153. (wrappedClass_.equals(((JavaClass) other).wrappedClass_)));
  154. }
  155. /* ------------------------------------------------------
  156. * - Symbiotic implementation of the ATObject interface -
  157. * ------------------------------------------------------ */
  158. /**
  159. * When a method is invoked upon a symbiotic Java class object, the underlying static Java method
  160. * with the same name as the AmbientTalk selector is invoked. Its arguments are converted
  161. * into their Java equivalents. Conversely, the result of the method invocation is converted
  162. * into an AmbientTalk object.
  163. */
  164. public ATObject meta_invoke(ATObject receiver, ATSymbol atSelector, ATTable arguments) throws InterpreterException {
  165. try {
  166. String jSelector = Reflection.upSelector(atSelector);
  167. return Symbiosis.symbioticInvocation(
  168. this, null, wrappedClass_, jSelector, arguments.asNativeTable().elements_);
  169. } catch (XSelectorNotFound e) {
  170. e.catchOnlyIfSelectorEquals(atSelector);
  171. return super.meta_invoke(receiver, atSelector, arguments);
  172. }
  173. }
  174. /**
  175. * A symbiotic Java class object responds to all of the public static selectors of its Java class
  176. * plus all of the per-instance selectors added to its AmbientTalk symbiont.
  177. */
  178. public ATBoolean meta_respondsTo(ATSymbol atSelector) throws InterpreterException {
  179. String jSelector = Reflection.upSelector(atSelector);
  180. if (Symbiosis.hasMethod(wrappedClass_, jSelector, true) ||
  181. Symbiosis.hasField(wrappedClass_, jSelector, true)) {
  182. return NATBoolean._TRUE_;
  183. } else {
  184. return super.meta_respondsTo(atSelector);
  185. }
  186. }
  187. /**
  188. * When selecting a field from a symbiotic Java class object, if the object's class
  189. * has a static field with a matching selector, it is automatically read;
  190. * if it has methods corresponding to the selector, they are returned in a JavaMethod wrapper,
  191. * otherwise, the fields of its AT symbiont are checked.
  192. */
  193. public ATObject meta_select(ATObject receiver, ATSymbol selector) throws InterpreterException {
  194. String jSelector = Reflection.upSelector(selector);
  195. try {
  196. return Symbiosis.readField(null, wrappedClass_, jSelector);
  197. } catch(XUndefinedField e) {
  198. JavaMethod choices = Symbiosis.getMethods(wrappedClass_, jSelector, true);
  199. if (choices != null) {
  200. return new JavaClosure(this, choices);
  201. } else {
  202. return super.meta_select(receiver, selector);
  203. }
  204. }
  205. }
  206. /**
  207. * A variable lookup is resolved by first checking whether the Java object has an appropriate static
  208. * field with a matching name. If so, that field's contents are returned. If not, the AT symbiont's
  209. * fields are checked.
  210. */
  211. public ATObject meta_lookup(ATSymbol selector) throws InterpreterException {
  212. try {
  213. String jSelector = Reflection.upSelector(selector);
  214. return Symbiosis.readField(null, wrappedClass_, jSelector);
  215. } catch(XUndefinedField e) {
  216. return super.meta_lookup(selector);
  217. }
  218. }
  219. /**
  220. * Fields can be defined within a symbiotic Java class object. They are added
  221. * to its AmbientTalk symbiont, but only if they do not clash with already
  222. * existing field names.
  223. */
  224. public ATNil meta_defineField(ATSymbol name, ATObject value) throws InterpreterException {
  225. if (Symbiosis.hasField(wrappedClass_, Reflection.upSelector(name), true)) {
  226. throw new XDuplicateSlot(XDuplicateSlot._FIELD_, name);
  227. } else {
  228. return super.meta_defineField(name, value);
  229. }
  230. }
  231. /**
  232. * Variables can be assigned within a symbiotic Java class object if that class object
  233. * has a mutable static field with a matching name. Variable assignment is first
  234. * resolved in the Java object and afterwards in the AT symbiont.
  235. */
  236. public ATNil meta_assignVariable(ATSymbol name, ATObject value) throws InterpreterException {
  237. try {
  238. String jSelector = Reflection.upSelector(name);
  239. Symbiosis.writeField(null, wrappedClass_, jSelector, value);
  240. return NATNil._INSTANCE_;
  241. } catch (XUnassignableField e) {
  242. return super.meta_assignVariable(name, value);
  243. }
  244. }
  245. /**
  246. * Fields can be assigned within a symbiotic Java class object if that class
  247. * has a mutable field with a matching name. Field assignment is first resolved
  248. * in the Java object and afterwards in the AT symbiont.
  249. */
  250. public ATNil meta_assignField(ATObject receiver, ATSymbol name, ATObject value) throws InterpreterException {
  251. try {
  252. String jSelector = Reflection.upSelector(name);
  253. Symbiosis.writeField(null, wrappedClass_, jSelector, value);
  254. return NATNil._INSTANCE_;
  255. } catch (XUnassignableField e) {
  256. return super.meta_assignField(receiver, name, value);
  257. }
  258. }
  259. /**
  260. * Symbiotic Java class objects are singletons.
  261. */
  262. public ATObject meta_clone() throws InterpreterException { return this; }
  263. /**
  264. * aJavaClass.new(@args) == invoke a Java constructor
  265. * AmbientTalk objects can add a custom new method to the class in order to intercept
  266. * instance creation. The original instance can then be performed by invoking the old new(@args).
  267. *
  268. * For example, imagine we want to extend the class java.lang.Point with a 3D coordinate, e.g. a 'z' field:
  269. * <tt>
  270. * def Point := jlobby.java.awt.Point;
  271. * def oldnew := Point.new;
  272. * def Point.new(x,y,z) { // 'override' the new method
  273. * def point := oldnew(x,y); // invokes the Java constructor
  274. * def point.z := z; // adds a field dynamically to the new JavaObject wrapper
  275. * point; // important! new should return the newly created instance
  276. * }
  277. * def mypoint := Point.new(1,2,3);
  278. * </tt>
  279. */
  280. public ATObject meta_newInstance(ATTable initargs) throws InterpreterException {
  281. return Symbiosis.symbioticInstanceCreation(wrappedClass_, initargs.asNativeTable().elements_);
  282. }
  283. /**
  284. * Methods can be added to a symbiotic Java class object provided they do not already
  285. * exist in the Java class.
  286. */
  287. public ATNil meta_addMethod(ATMethod method) throws InterpreterException {
  288. ATSymbol name = method.base_getName();
  289. if (Symbiosis.hasMethod(wrappedClass_, Reflection.upSelector(name), true)) {
  290. throw new XDuplicateSlot(XDuplicateSlot._METHOD_, name);
  291. } else {
  292. return super.meta_addMethod(method);
  293. }
  294. }
  295. /**
  296. * Fields can be grabbed from a symbiotic Java class object. Fields that correspond
  297. * to static fields in the Java class are returned as JavaField instances.
  298. */
  299. public ATField meta_grabField(ATSymbol fieldName) throws InterpreterException {
  300. try {
  301. return new JavaField(null,
  302. Symbiosis.getField(wrappedClass_, Reflection.upSelector(fieldName), true));
  303. } catch(XUndefinedField e) {
  304. return super.meta_grabField(fieldName);
  305. }
  306. }
  307. /**
  308. * Methods can be grabbed from a symbiotic Java class object. Methods that correspond
  309. * to static methods in the Java class are returned as JavaMethod instances.
  310. */
  311. public ATMethod meta_grabMethod(ATSymbol methodName) throws InterpreterException {
  312. JavaMethod choices = Symbiosis.getMethods(wrappedClass_, Reflection.upSelector(methodName), true);
  313. if (choices != null) {
  314. return choices;
  315. } else {
  316. return super.meta_grabMethod(methodName);
  317. }
  318. }
  319. /**
  320. * Querying a symbiotic Java class object for its fields results in a table containing
  321. * both 'native' static Java fields and the fields of its AT symbiont
  322. */
  323. public ATTable meta_listFields() throws InterpreterException {
  324. // instance fields of the wrapped object's class
  325. JavaField[] jFields = Symbiosis.getAllFields(null, wrappedClass_);
  326. // fields of the AT symbiont
  327. ATObject[] symbiontFields = super.meta_listFields().asNativeTable().elements_;
  328. return NATTable.atValue(NATTable.collate(jFields, symbiontFields));
  329. }
  330. /**
  331. * Querying a symbiotic Java class object for its methods results in a table containing
  332. * both 'native' static Java methods and the methods of its AT symbiont
  333. */
  334. public ATTable meta_listMethods() throws InterpreterException {
  335. // instance methods of the wrapped object's class
  336. JavaMethod[] jMethods = Symbiosis.getAllMethods(wrappedClass_, true);
  337. // methods of the AT symbiont
  338. ATObject[] symbiontMethods = super.meta_listMethods().asNativeTable().elements_;
  339. return NATTable.atValue(NATTable.collate(jMethods, symbiontMethods));
  340. }
  341. public ATBoolean meta_isCloneOf(ATObject original) throws InterpreterException {
  342. return NATBoolean.atValue(this == original);
  343. }
  344. public NATText meta_print() throws InterpreterException {
  345. return NATText.atValue("<java:"+wrappedClass_.toString()+">");
  346. }
  347. /**
  348. * A Java Class object remains unique within an actor.
  349. */
  350. public ATObject meta_resolve() throws InterpreterException {
  351. return wrapperFor(wrappedClass_);
  352. }
  353. /* ========================
  354. * == ATStripe Interface ==
  355. * ======================== */
  356. /**
  357. * If this class represents an interface type, parentStripes
  358. * are wrappers for all interfaces extended by this Java interface type
  359. */
  360. public ATTable base_getParentStripes() throws InterpreterException {
  361. return super.meta_select(this, _PST_NAME_).asTable();
  362. }
  363. public ATSymbol base_getStripeName() throws InterpreterException {
  364. return super.meta_select(this, _SNM_NAME_).asSymbol();
  365. }
  366. /**
  367. * A Java interface type used as a stripe can only be a substripe of another
  368. * Java interface type used as a stripe, and only if this type is assignable
  369. * to the other type.
  370. */
  371. public ATBoolean base_isSubstripeOf(ATStripe other) throws InterpreterException {
  372. if (other instanceof JavaClass) {
  373. JavaClass otherClass = (JavaClass) other;
  374. // wrappedClass <: otherClass <=> otherClass >= wrappedClass
  375. return NATBoolean.atValue(otherClass.wrappedClass_.isAssignableFrom(wrappedClass_));
  376. } else {
  377. return NATBoolean._FALSE_;
  378. }
  379. }
  380. }