7
$\begingroup$

How can I discover which path is read to load some Java class using the command: LoadJavaClass["my.java.class"]?

I believe all JavaClassPath[] is scanned, but which is used?

$\endgroup$

1 Answer 1

7
$\begingroup$

Update 2023-06-16: It is reported that the following response no longer works when using Mathematica 13.2 on MacOS.

The following function can be used to recover the resource URL that contains a given class:

Needs["JLink`"]
InstallJava[];
LoadJavaClass["com.wolfram.jlink.JLinkClassLoader"];

classResourceUrl[className_] :=
  JavaBlock @ Module[{resourceName, loader}
  , resourceName = StringReplace[className, "."->"/"]~~".class"
  ; loader =
      com`wolfram`jlink`JLinkClassLoader`classFromName[className] @ getClassLoader[] /.
        Null :> com`wolfram`jlink`JLinkClassLoaderHelper`getSystemClassLoader[]
  ; loader@getResource[resourceName] /. url:Except[Null] :> url@toString[]
  ]

It works by:

  1. Using JLinkClassLoader to recover the Java class object.
  2. Getting the class' classloader (Null indicating the system classloader).
  3. Using that classloader to get the URL of the class' binary name.

Here it is in action:

classResourceUrl["org.hsqldb.jdbc.JDBCDriver"]

(* jar:file:/C:/Program%20Files/Wolfram%20Research/Mathematica/10.2/
   SystemFiles/Links/DatabaseLink/Java/hsqldb.jar!
   /org/hsqldb/jdbc/JDBCDriver.class *)

classResourceUrl["org.rosuda.JRI.Rengine"]

(* jar:file:/C:/Program%20Files/Wolfram%20Research/Mathematica/10.2/
   SystemFiles/Links/RLink/Java/JRI.jar!
   /org/rosuda/JRI/Rengine.class *)

AddToClassPath @ "C:\\eclipse\\plugins\\org.junit_4.10.0\\junit.jar";
classResourceUrl["org.junit.Assert"]

(* jar:file:/C:/eclipse/plugins/org.junit_4.10.0/junit.jar!
   /org/junit/Assert.class *)
$\endgroup$
5
  • $\begingroup$ This is very useful. Tks +1 $\endgroup$
    – Murta
    Commented Jul 27, 2015 at 3:22
  • $\begingroup$ Thanks. This was useful to diagnose conflicts! $\endgroup$ Commented Jan 25, 2018 at 19:35
  • $\begingroup$ I do not think this solution works anymore. (At least on macOS.) $\endgroup$ Commented Jun 14, 2023 at 17:49
  • $\begingroup$ @AntonAntonov Thanks for the info. Unfortunately, I no longer have access to recent versions of Mathematica so I can take this no further. If you can say which version(s) you know are broken, I can put a disclaimer at the top of the response. $\endgroup$
    – WReach
    Commented Jun 14, 2023 at 20:10
  • $\begingroup$ I used Mathematica version 13.2 on macOS. (Thanks!) $\endgroup$ Commented Jun 16, 2023 at 15:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.