Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -22,22 +22,28 @@ import java.util.ServiceLoader
import scala.collection.JavaConverters._
import scala.language.existentials
import scala.reflect.ClassTag
import scala.util.Try

object ReflectUtils {

/**
* Determines whether the provided class is loadable
* Determines whether the provided class is loadable, answering false when it cannot
* be found, linked, or initialized.
* @param className the class name
* @param cl the class loader
* @return is the class name loadable with the class loader
*/
def isClassLoadable(
className: String,
cl: ClassLoader = Thread.currentThread().getContextClassLoader): Boolean =
Try {
try {
DynClasses.builder().loader(cl).impl(className).buildChecked()
}.isSuccess
true
} catch {
// scala.util.Try does not catch LinkageError, so a class that fails to link or
// initialize would escape the probe instead of answering false
case _: ClassNotFoundException => false
case _: LinkageError => false
}

/**
* get the field value of the given object
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,15 @@ class ReflectUtilsSuite extends AnyFunSuite {
assert(!isClassLoadable("org.apache.kyuubi.NonExistClass"))
}

test("check class that fails to initialize is not loadable") {
// Class.forName reports a failing static initializer as ExceptionInInitializerError,
// a LinkageError that Try does not catch; a loadability probe must answer false
// instead of letting the error escape
// probe by binary name: touching the object reference would run the failing
// initialization outside the code under test and abort the suite
assert(!isClassLoadable("org.apache.kyuubi.util.reflect.FailingInit$"))
}

test("check invokeAs on base class") {
assertResult("method1")(invokeAs[String](obj1, "method1"))
assertResult("method2")(invokeAs[String](obj1, "method2"))
Expand Down Expand Up @@ -103,3 +112,7 @@ object ObjectA {
def method5(): String = "method5"
private def method6(): String = "method6"
}

object FailingInit {
throw new IllegalStateException("static init failed")
}
Loading