| author | wenzelm | 
| Tue, 29 Sep 2015 16:58:33 +0200 | |
| changeset 61280 | 12f9ab87a06d | 
| parent 59080 | 611914621edb | 
| child 63419 | f473b6b16c63 | 
| permissions | -rw-r--r-- | 
| 56905 | 1 | /* Title: Pure/General/untyped.scala | 
| 2 | Module: PIDE | |
| 3 | Author: Makarius | |
| 4 | ||
| 5 | Untyped, unscoped, unchecked access to JVM objects. | |
| 6 | */ | |
| 7 | ||
| 8 | package isabelle | |
| 9 | ||
| 10 | ||
| 59080 
611914621edb
added Untyped.method convenience (for *this* class only);
 wenzelm parents: 
59079diff
changeset | 11 | import java.lang.reflect.Method | 
| 
611914621edb
added Untyped.method convenience (for *this* class only);
 wenzelm parents: 
59079diff
changeset | 12 | |
| 
611914621edb
added Untyped.method convenience (for *this* class only);
 wenzelm parents: 
59079diff
changeset | 13 | |
| 56905 | 14 | object Untyped | 
| 15 | {
 | |
| 59080 
611914621edb
added Untyped.method convenience (for *this* class only);
 wenzelm parents: 
59079diff
changeset | 16 | def method(c: Class[_], name: String, arg_types: Class[_]*): Method = | 
| 
611914621edb
added Untyped.method convenience (for *this* class only);
 wenzelm parents: 
59079diff
changeset | 17 |   {
 | 
| 
611914621edb
added Untyped.method convenience (for *this* class only);
 wenzelm parents: 
59079diff
changeset | 18 | val m = c.getDeclaredMethod(name, arg_types: _*) | 
| 
611914621edb
added Untyped.method convenience (for *this* class only);
 wenzelm parents: 
59079diff
changeset | 19 | m.setAccessible(true) | 
| 
611914621edb
added Untyped.method convenience (for *this* class only);
 wenzelm parents: 
59079diff
changeset | 20 | m | 
| 
611914621edb
added Untyped.method convenience (for *this* class only);
 wenzelm parents: 
59079diff
changeset | 21 | } | 
| 
611914621edb
added Untyped.method convenience (for *this* class only);
 wenzelm parents: 
59079diff
changeset | 22 | |
| 58682 | 23 |   def classes(obj: AnyRef): Iterator[Class[_ <: AnyRef]] = new Iterator[Class[_ <: AnyRef]] {
 | 
| 24 | private var next_elem: Class[_ <: AnyRef] = obj.getClass | |
| 25 | def hasNext(): Boolean = next_elem != null | |
| 26 |     def next(): Class[_ <: AnyRef] = {
 | |
| 27 | val c = next_elem | |
| 28 | next_elem = c.getSuperclass.asInstanceOf[Class[_ <: AnyRef]] | |
| 29 | c | |
| 56905 | 30 | } | 
| 31 | } | |
| 58682 | 32 | |
| 59079 | 33 | def get[A](obj: AnyRef, x: String): A = | 
| 34 | if (obj == null) null.asInstanceOf[A] | |
| 58682 | 35 |     else {
 | 
| 36 | val iterator = | |
| 37 |         for {
 | |
| 38 | c <- classes(obj) | |
| 39 | field <- c.getDeclaredFields.iterator | |
| 40 | if field.getName == x | |
| 41 |         } yield {
 | |
| 42 | field.setAccessible(true) | |
| 43 | field.get(obj) | |
| 44 | } | |
| 59079 | 45 | if (iterator.hasNext) iterator.next.asInstanceOf[A] | 
| 58682 | 46 |       else error("No field " + quote(x) + " for " + obj)
 | 
| 47 | } | |
| 56905 | 48 | } | 
| 49 |