Skip to content

Commit 7168743

Browse files
committed
Added ensureAccessible to reflection library.
This method comes up with some frequency and there are a lot of ways to write it either unsafely (failing to catch a likely exception) or with inadequate generality (as was done in the pre-existing version of this method in ScalaRunTime) so I thought it warranted a place in the standard library.
1 parent b575c1e commit 7168743

File tree

2 files changed

+15
-7
lines changed

2 files changed

+15
-7
lines changed

src/library/scala/reflect/package.scala

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package scala
22

3+
import java.lang.reflect.{ AccessibleObject => jAccessibleObject }
4+
35
package object reflect {
46

57
// in the new scheme of things ClassManifests are aliased to ClassTags
@@ -42,6 +44,18 @@ package object reflect {
4244

4345
def classTag[T](implicit ctag: ClassTag[T]) = ctag
4446

47+
/** Make a java reflection object accessible, if it is not already
48+
* and it is possible to do so. If a SecurityException is thrown in the
49+
* attempt, it is caught and discarded.
50+
*/
51+
def ensureAccessible[T <: jAccessibleObject](m: T): T = {
52+
if (!m.isAccessible) {
53+
try m setAccessible true
54+
catch { case _: SecurityException => } // does nothing
55+
}
56+
m
57+
}
58+
4559
// anchor for the class tag materialization macro emitted during tag materialization in Implicits.scala
4660
// implementation is hardwired into `scala.reflect.reify.Taggers`
4761
// using the mechanism implemented in `scala.tools.reflect.FastTrack`

src/library/scala/runtime/ScalaRunTime.scala

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -158,13 +158,7 @@ object ScalaRunTime {
158158

159159
// Java bug: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4071957
160160
// More background at ticket #2318.
161-
def ensureAccessible(m: JMethod): JMethod = {
162-
if (!m.isAccessible) {
163-
try m setAccessible true
164-
catch { case _: SecurityException => () }
165-
}
166-
m
167-
}
161+
def ensureAccessible(m: JMethod): JMethod = scala.reflect.ensureAccessible(m)
168162

169163
def checkInitialized[T <: AnyRef](x: T): T =
170164
if (x == null) throw new UninitializedError else x

0 commit comments

Comments
 (0)