author | wenzelm |
Fri, 01 Apr 2022 17:06:10 +0200 | |
changeset 75393 | 87ebf5a50283 |
parent 73344 | f5c147654661 |
child 75408 | e859c9f30db2 |
permissions | -rw-r--r-- |
56905 | 1 |
/* Title: Pure/General/untyped.scala |
2 |
Author: Makarius |
|
3 |
||
4 |
Untyped, unscoped, unchecked access to JVM objects. |
|
5 |
*/ |
|
6 |
||
7 |
package isabelle |
|
8 |
||
9 |
||
72973 | 10 |
import java.lang.reflect.{Constructor, Method, Field} |
59080
611914621edb
added Untyped.method convenience (for *this* class only);
wenzelm
parents:
59079
diff
changeset
|
11 |
|
611914621edb
added Untyped.method convenience (for *this* class only);
wenzelm
parents:
59079
diff
changeset
|
12 |
|
75393 | 13 |
object Untyped { |
14 |
def constructor[C](c: Class[C], arg_types: Class[_]*): Constructor[C] = { |
|
72973 | 15 |
val con = c.getDeclaredConstructor(arg_types: _*) |
16 |
con.setAccessible(true) |
|
17 |
con |
|
18 |
} |
|
19 |
||
75393 | 20 |
def method(c: Class[_], name: String, arg_types: Class[_]*): Method = { |
59080
611914621edb
added Untyped.method convenience (for *this* class only);
wenzelm
parents:
59079
diff
changeset
|
21 |
val m = c.getDeclaredMethod(name, arg_types: _*) |
611914621edb
added Untyped.method convenience (for *this* class only);
wenzelm
parents:
59079
diff
changeset
|
22 |
m.setAccessible(true) |
611914621edb
added Untyped.method convenience (for *this* class only);
wenzelm
parents:
59079
diff
changeset
|
23 |
m |
611914621edb
added Untyped.method convenience (for *this* class only);
wenzelm
parents:
59079
diff
changeset
|
24 |
} |
611914621edb
added Untyped.method convenience (for *this* class only);
wenzelm
parents:
59079
diff
changeset
|
25 |
|
58682 | 26 |
def classes(obj: AnyRef): Iterator[Class[_ <: AnyRef]] = new Iterator[Class[_ <: AnyRef]] { |
27 |
private var next_elem: Class[_ <: AnyRef] = obj.getClass |
|
73337 | 28 |
def hasNext: Boolean = next_elem != null |
58682 | 29 |
def next(): Class[_ <: AnyRef] = { |
30 |
val c = next_elem |
|
31 |
next_elem = c.getSuperclass.asInstanceOf[Class[_ <: AnyRef]] |
|
32 |
c |
|
56905 | 33 |
} |
34 |
} |
|
58682 | 35 |
|
75393 | 36 |
def field(obj: AnyRef, x: String): Field = { |
63419 | 37 |
val iterator = |
38 |
for { |
|
39 |
c <- classes(obj) |
|
40 |
field <- c.getDeclaredFields.iterator |
|
41 |
if field.getName == x |
|
42 |
} yield { |
|
43 |
field.setAccessible(true) |
|
44 |
field |
|
45 |
} |
|
73344 | 46 |
if (iterator.hasNext) iterator.next() |
63419 | 47 |
else error("No field " + quote(x) + " for " + obj) |
48 |
} |
|
49 |
||
59079 | 50 |
def get[A](obj: AnyRef, x: String): A = |
51 |
if (obj == null) null.asInstanceOf[A] |
|
63419 | 52 |
else field(obj, x).get(obj).asInstanceOf[A] |
53 |
||
54 |
def set[A](obj: AnyRef, x: String, y: A): Unit = |
|
55 |
field(obj, x).set(obj, y) |
|
56905 | 56 |
} |