author | wenzelm |
Thu, 07 Jul 2016 11:46:18 +0200 | |
changeset 63419 | f473b6b16c63 |
parent 59080 | 611914621edb |
child 64370 | 865b39487b5d |
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 |
||
63419 | 11 |
import java.lang.reflect.{Method, Field} |
59080
611914621edb
added Untyped.method convenience (for *this* class only);
wenzelm
parents:
59079
diff
changeset
|
12 |
|
611914621edb
added Untyped.method convenience (for *this* class only);
wenzelm
parents:
59079
diff
changeset
|
13 |
|
56905 | 14 |
object Untyped |
15 |
{ |
|
59080
611914621edb
added Untyped.method convenience (for *this* class only);
wenzelm
parents:
59079
diff
changeset
|
16 |
def method(c: Class[_], name: String, arg_types: Class[_]*): Method = |
611914621edb
added Untyped.method convenience (for *this* class only);
wenzelm
parents:
59079
diff
changeset
|
17 |
{ |
611914621edb
added Untyped.method convenience (for *this* class only);
wenzelm
parents:
59079
diff
changeset
|
18 |
val m = c.getDeclaredMethod(name, arg_types: _*) |
611914621edb
added Untyped.method convenience (for *this* class only);
wenzelm
parents:
59079
diff
changeset
|
19 |
m.setAccessible(true) |
611914621edb
added Untyped.method convenience (for *this* class only);
wenzelm
parents:
59079
diff
changeset
|
20 |
m |
611914621edb
added Untyped.method convenience (for *this* class only);
wenzelm
parents:
59079
diff
changeset
|
21 |
} |
611914621edb
added Untyped.method convenience (for *this* class only);
wenzelm
parents:
59079
diff
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 |
|
63419 | 33 |
def field(obj: AnyRef, x: String): Field = |
34 |
{ |
|
35 |
val iterator = |
|
36 |
for { |
|
37 |
c <- classes(obj) |
|
38 |
field <- c.getDeclaredFields.iterator |
|
39 |
if field.getName == x |
|
40 |
} yield { |
|
41 |
field.setAccessible(true) |
|
42 |
field |
|
43 |
} |
|
44 |
if (iterator.hasNext) iterator.next |
|
45 |
else error("No field " + quote(x) + " for " + obj) |
|
46 |
} |
|
47 |
||
59079 | 48 |
def get[A](obj: AnyRef, x: String): A = |
49 |
if (obj == null) null.asInstanceOf[A] |
|
63419 | 50 |
else field(obj, x).get(obj).asInstanceOf[A] |
51 |
||
52 |
def set[A](obj: AnyRef, x: String, y: A): Unit = |
|
53 |
field(obj, x).set(obj, y) |
|
56905 | 54 |
} |