/interpreter/tags/at2-build270707/src/edu/vub/at/objects/symbiosis/JavaClass.java

http://ambienttalk.googlecode.com/ · Java · 377 lines · 197 code · 40 blank · 140 comment · 21 complexity · 65bb20dc6fc756028e7860c8a38d6ff7 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.exceptions.InterpreterException;
  30. import edu.vub.at.exceptions.XArityMismatch;
  31. import edu.vub.at.exceptions.XDuplicateSlot;
  32. import edu.vub.at.exceptions.XTypeMismatch;
  33. import edu.vub.at.exceptions.XUnassignableField;
  34. import edu.vub.at.exceptions.XUndefinedSlot;
  35. import edu.vub.at.objects.ATBoolean;
  36. import edu.vub.at.objects.ATContext;
  37. import edu.vub.at.objects.ATField;
  38. import edu.vub.at.objects.ATMethod;
  39. import edu.vub.at.objects.ATNil;
  40. import edu.vub.at.objects.ATObject;
  41. import edu.vub.at.objects.ATTable;
  42. import edu.vub.at.objects.ATTypeTag;
  43. import edu.vub.at.objects.coercion.NativeTypeTags;
  44. import edu.vub.at.objects.grammar.ATSymbol;
  45. import edu.vub.at.objects.mirrors.PrimitiveMethod;
  46. import edu.vub.at.objects.mirrors.Reflection;
  47. import edu.vub.at.objects.natives.NATBoolean;
  48. import edu.vub.at.objects.natives.NATNumber;
  49. import edu.vub.at.objects.natives.NATObject;
  50. import edu.vub.at.objects.natives.NATTable;
  51. import edu.vub.at.objects.natives.NATText;
  52. import edu.vub.at.objects.natives.grammar.AGSymbol;
  53. import edu.vub.at.util.logging.Logging;
  54. import edu.vub.util.IdentityHashMap;
  55. import java.io.IOException;
  56. import java.lang.ref.SoftReference;
  57. /**
  58. * A JavaClass instance represents a Java Class under symbiosis.
  59. *
  60. * Java classes are treated as AmbientTalk 'singleton' objects:
  61. *
  62. * - cloning a Java class results in the same Java class instance
  63. * - sending 'new' to a Java class invokes the constructor and returns a new instance of the class under symbiosis
  64. * - all static fields and methods of the Java class are reflected under symbiosis as fields and methods of the AT object
  65. *
  66. * A Java Class object that represents an interface can furthermore be used
  67. * as an AmbientTalk type. The type's name corresponds to the interface's full name.
  68. *
  69. * JavaClass instances are pooled (on a per-actor basis): there should exist only one JavaClass instance
  70. * for each Java class loaded into the JVM. Because the JVM ensures that a Java class
  71. * can only be loaded once, we can use the Java class wrapped by the JavaClass instance
  72. * as a unique key to identify its corresponding JavaClass instance.
  73. *
  74. * @author tvcutsem
  75. */
  76. public final class JavaClass extends NATObject implements ATTypeTag {
  77. /**
  78. * A thread-local hashmap pooling all of the JavaClass wrappers for
  79. * the current actor, referring to them using SOFT references, such
  80. * that unused wrappers can be GC-ed when running low on memory.
  81. */
  82. private static final ThreadLocal _JAVACLASS_POOL_ = new ThreadLocal() {
  83. protected synchronized Object initialValue() {
  84. return new IdentityHashMap();
  85. }
  86. };
  87. /**
  88. * Allocate a unique symbiont object for the given Java class.
  89. */
  90. public static final JavaClass wrapperFor(Class c) {
  91. IdentityHashMap map = (IdentityHashMap) _JAVACLASS_POOL_.get();
  92. if (map.containsKey(c)) {
  93. SoftReference ref = (SoftReference) map.get(c);
  94. JavaClass cls = (JavaClass) ref.get();
  95. if (cls != null) {
  96. return cls;
  97. } else {
  98. map.remove(c);
  99. cls = new JavaClass(c);
  100. map.put(c, new SoftReference(cls));
  101. return cls;
  102. }
  103. } else {
  104. JavaClass jc = new JavaClass(c);
  105. map.put(c, new SoftReference(jc));
  106. return jc;
  107. }
  108. }
  109. // primitive fields and method of a JavaClass wrapper
  110. private static final AGSymbol _PTS_NAME_ = AGSymbol.jAlloc("parentTypes");
  111. private static final AGSymbol _TNM_NAME_ = AGSymbol.jAlloc("typeName");
  112. /** def isSubtypeOf(type) { nil } */
  113. private static final PrimitiveMethod _PRIM_STP_ = new PrimitiveMethod(
  114. AGSymbol.jAlloc("isSubtypeOf"), NATTable.atValue(new ATObject[] { AGSymbol.jAlloc("type")})) {
  115. private static final long serialVersionUID = -6864350539143194204L;
  116. public ATObject base_apply(ATTable arguments, ATContext ctx) throws InterpreterException {
  117. if (!arguments.base_length().equals(NATNumber.ONE)) {
  118. throw new XArityMismatch("isSubtypeOf", 1, arguments.base_length().asNativeNumber().javaValue);
  119. }
  120. return ctx.base_lexicalScope().asJavaClassUnderSymbiosis().base_isSubtypeOf(arguments.base_at(NATNumber.ONE).asTypeTag());
  121. }
  122. };
  123. private final Class wrappedClass_;
  124. /**
  125. * A JavaClass wrapping a class c is an object that has the lexical scope as its lexical parent
  126. * and has NIL as its dynamic parent.
  127. *
  128. * If the JavaClass wraps a Java interface type, JavaClass instances are
  129. * also types.
  130. */
  131. private JavaClass(Class wrappedClass) {
  132. super(wrappedClass.isInterface() ?
  133. new ATTypeTag[] { NativeTypeTags._TYPETAG_, NativeTypeTags._ISOLATE_ } :
  134. NATObject._NO_TYPETAGS_);
  135. wrappedClass_ = wrappedClass;
  136. // add the two fields and one method needed for an ATTypeTag
  137. if (wrappedClass.isInterface()) {
  138. Class[] extendedInterfaces = wrappedClass_.getInterfaces();
  139. ATObject[] types = new ATObject[extendedInterfaces.length];
  140. for (int i = 0; i < extendedInterfaces.length; i++) {
  141. types[i] = JavaClass.wrapperFor(extendedInterfaces[i]);
  142. }
  143. try {
  144. super.meta_defineField(_PTS_NAME_, NATTable.atValue(types));
  145. super.meta_defineField(_TNM_NAME_, AGSymbol.jAlloc(wrappedClass_.getName()));
  146. super.meta_addMethod(_PRIM_STP_);
  147. } catch (InterpreterException e) {
  148. Logging.Actor_LOG.fatal("Error while initializing Java Class as type tag: " + wrappedClass.getName(), e);
  149. }
  150. }
  151. }
  152. /** return the class object denoted by this AmbientTalk symbiont */
  153. public Class getWrappedClass() { return wrappedClass_; }
  154. public JavaClass asJavaClassUnderSymbiosis() throws XTypeMismatch { return this; }
  155. public ATBoolean base__opeql__opeql_(ATObject comparand) throws InterpreterException {
  156. return NATBoolean.atValue(this.equals(comparand));
  157. }
  158. public boolean equals(Object other) {
  159. return ((other instanceof JavaClass) &&
  160. (wrappedClass_.equals(((JavaClass) other).wrappedClass_)));
  161. }
  162. /**
  163. * Fields can be defined within a symbiotic Java class object. They are added
  164. * to its AmbientTalk symbiont, but only if they do not clash with already
  165. * existing field names.
  166. */
  167. public ATNil meta_defineField(ATSymbol name, ATObject value) throws InterpreterException {
  168. if (Symbiosis.hasField(wrappedClass_, Reflection.upSelector(name), true)) {
  169. throw new XDuplicateSlot(name);
  170. } else {
  171. return super.meta_defineField(name, value);
  172. }
  173. }
  174. /**
  175. * Symbiotic Java class objects are singletons.
  176. */
  177. public ATObject meta_clone() throws InterpreterException { return this; }
  178. /**
  179. * aJavaClass.new(@args) == invoke a Java constructor
  180. * AmbientTalk objects can add a custom new method to the class in order to intercept
  181. * instance creation. The original instance can then be performed by invoking the old new(@args).
  182. *
  183. * For example, imagine we want to extend the class java.lang.Point with a 3D coordinate, e.g. a 'z' field:
  184. * <tt>
  185. * def Point := jlobby.java.awt.Point;
  186. * def oldnew := Point.new;
  187. * def Point.new(x,y,z) { // 'override' the new method
  188. * def point := oldnew(x,y); // invokes the Java constructor
  189. * def point.z := z; // adds a field dynamically to the new JavaObject wrapper
  190. * point; // important! new should return the newly created instance
  191. * }
  192. * def mypoint := Point.new(1,2,3);
  193. * </tt>
  194. */
  195. public ATObject meta_newInstance(ATTable initargs) throws InterpreterException {
  196. return Symbiosis.symbioticInstanceCreation(wrappedClass_, initargs.asNativeTable().elements_);
  197. }
  198. /**
  199. * Methods can be added to a symbiotic Java class object provided they do not already
  200. * exist in the Java class.
  201. */
  202. public ATNil meta_addMethod(ATMethod method) throws InterpreterException {
  203. ATSymbol name = method.base_name();
  204. if (Symbiosis.hasMethod(wrappedClass_, Reflection.upSelector(name), true)) {
  205. throw new XDuplicateSlot(name);
  206. } else {
  207. return super.meta_addMethod(method);
  208. }
  209. }
  210. /**
  211. * Fields can be grabbed from a symbiotic Java class object. Fields that correspond
  212. * to static fields in the Java class are returned as JavaField instances.
  213. */
  214. public ATField meta_grabField(ATSymbol fieldName) throws InterpreterException {
  215. try {
  216. return new JavaField(null,
  217. Symbiosis.getField(wrappedClass_, Reflection.upSelector(fieldName), true));
  218. } catch(XUndefinedSlot e) {
  219. return super.meta_grabField(fieldName);
  220. }
  221. }
  222. /**
  223. * Methods can be grabbed from a symbiotic Java class object. Methods that correspond
  224. * to static methods in the Java class are returned as JavaMethod instances.
  225. */
  226. public ATMethod meta_grabMethod(ATSymbol methodName) throws InterpreterException {
  227. JavaMethod choices = Symbiosis.getMethods(wrappedClass_, Reflection.upSelector(methodName), true);
  228. if (choices != null) {
  229. return choices;
  230. } else {
  231. return super.meta_grabMethod(methodName);
  232. }
  233. }
  234. /**
  235. * Querying a symbiotic Java class object for its fields results in a table containing
  236. * both 'native' static Java fields and the fields of its AT symbiont
  237. */
  238. public ATTable meta_listFields() throws InterpreterException {
  239. // instance fields of the wrapped object's class
  240. JavaField[] jFields = Symbiosis.getAllFields(null, wrappedClass_);
  241. // fields of the AT symbiont
  242. ATObject[] symbiontFields = super.meta_listFields().asNativeTable().elements_;
  243. return NATTable.atValue(NATTable.collate(jFields, symbiontFields));
  244. }
  245. /**
  246. * Querying a symbiotic Java class object for its methods results in a table containing
  247. * both 'native' static Java methods and the methods of its AT symbiont
  248. */
  249. public ATTable meta_listMethods() throws InterpreterException {
  250. // instance methods of the wrapped object's class
  251. JavaMethod[] jMethods = Symbiosis.getAllMethods(wrappedClass_, true);
  252. // methods of the AT symbiont
  253. ATObject[] symbiontMethods = super.meta_listMethods().asNativeTable().elements_;
  254. return NATTable.atValue(NATTable.collate(jMethods, symbiontMethods));
  255. }
  256. public ATBoolean meta_isCloneOf(ATObject original) throws InterpreterException {
  257. return NATBoolean.atValue(this == original);
  258. }
  259. public NATText meta_print() throws InterpreterException {
  260. return NATText.atValue("<java:"+wrappedClass_.toString()+">");
  261. }
  262. /**
  263. * A Java Class object remains unique within an actor.
  264. */
  265. public ATObject meta_resolve() throws InterpreterException {
  266. return wrapperFor(wrappedClass_);
  267. }
  268. /* ========================
  269. * == ATTypeTag Interface ==
  270. * ======================== */
  271. /**
  272. * If this class represents an interface type, parentTypes
  273. * are wrappers for all interfaces extended by this Java interface type
  274. */
  275. public ATTable base_superTypes() throws InterpreterException {
  276. return super.impl_invokeAccessor(this, _PTS_NAME_, NATTable.EMPTY).asTable();
  277. }
  278. public ATSymbol base_typeName() throws InterpreterException {
  279. return super.impl_invokeAccessor(this, _TNM_NAME_, NATTable.EMPTY).asSymbol();
  280. }
  281. /**
  282. * A Java interface type used as a type can only be a subtype of another
  283. * Java interface type used as a type, and only if this type is assignable
  284. * to the other type.
  285. */
  286. public ATBoolean base_isSubtypeOf(ATTypeTag other) throws InterpreterException {
  287. if (other instanceof JavaClass) {
  288. JavaClass otherClass = (JavaClass) other;
  289. // wrappedClass <: otherClass <=> otherClass >= wrappedClass
  290. return NATBoolean.atValue(otherClass.wrappedClass_.isAssignableFrom(wrappedClass_));
  291. } else {
  292. return NATBoolean._FALSE_;
  293. }
  294. }
  295. // IMPLEMENTATION INTERFACE
  296. /**
  297. * A symbiotic Java class object has all of the public static fields
  298. * of its Java class plus all of the fields defined in the AT symbiont.
  299. */
  300. protected boolean hasLocalField(ATSymbol atSelector) throws InterpreterException {
  301. return Symbiosis.hasField(wrappedClass_, Reflection.upSelector(atSelector), true) ||
  302. super.hasLocalField(atSelector);
  303. }
  304. /**
  305. * A symbiotic Java class object has all of the public static methods
  306. * of its Java class plus all of the methods defined in the AT symbiont.
  307. */
  308. protected boolean hasLocalMethod(ATSymbol atSelector) throws InterpreterException {
  309. return Symbiosis.hasMethod(wrappedClass_, Reflection.upSelector(atSelector), true) ||
  310. super.hasLocalMethod(atSelector);
  311. }
  312. protected ATObject getLocalField(ATSymbol selector) throws InterpreterException {
  313. try {
  314. return Symbiosis.readField(null, wrappedClass_, Reflection.upSelector(selector));
  315. } catch(XUndefinedSlot e) {
  316. return super.getLocalField(selector);
  317. }
  318. }
  319. protected ATMethod getLocalMethod(ATSymbol methodName) throws InterpreterException {
  320. JavaMethod choices = Symbiosis.getMethods(wrappedClass_, Reflection.upSelector(methodName), true);
  321. if (choices != null) {
  322. return choices;
  323. } else {
  324. return super.getLocalMethod(methodName);
  325. }
  326. }
  327. protected void setLocalField(ATSymbol selector, ATObject value) throws InterpreterException {
  328. try {
  329. Symbiosis.writeField(null, wrappedClass_, Reflection.upSelector(selector), value);
  330. } catch(XUndefinedSlot e) {
  331. super.setLocalField(selector, value);
  332. } catch(XUnassignableField e) {
  333. // field may have been final, in which case there 'is no such field'
  334. super.setLocalField(selector, value);
  335. }
  336. }
  337. }