0

I have a staff class in Java and I can get the location on disk where it was loaded from using the following code:

Staff.class.getProtectionDomain().getCodeSource().getLocation();

In a jruby jirb session I tried the following:

Staff.getProtectionDomain()

and (edit)

Staff.class.getProtectionDomain()

both of which cannot find the method: undefined method `getProtectionDomain'

Is this method masked by jruby and if so, how can I call it?

[edit] I am using jruby 1.5.6.

Tony Eichelberger
  • 7,044
  • 7
  • 37
  • 46

3 Answers3

1

In jruby you should use #protection_domain() - which exists and works as expected - instead of getProtectionDomain() - which exists but does not work as expected.

For completeness, here is a short example:

# use this to get the jruby-complete.jar file
a_java_class = self.to_java.java_class
  #=> class org.jruby.RubyObject
a_java_class.protection_domain.code_source.location.path
  #=> "/C:/Users/xxx/yyy/jruby-complete-9.0.4.0.jar"


# use this to get the file path to the commons-lang3-3.4.jar
require_relative 'java_lib/commons-lang3-3.4.jar'
a_java_class = Java::org.apache.commons.lang3.SystemUtils.java_class
  #=> class org.apache.commons.lang3.SystemUtils
a_java_class.protection_domain.code_source.location.path
  #=>"/C:/Users/xxx/yyy/zzz/java_lib/commons-lang3-3.4.jar"

Also, see this other post with related info: Get JRuby jar path

Community
  • 1
  • 1
zipizap
  • 633
  • 6
  • 13
0

I believe it should be Staff.class.getProtectionDomain() in jruby as well.

  • Solution: 1) Staff should be a *java class* from a jar file; 2) in jruby avoid the java method `#getProtectionDomain()` and instead use jruby's method `#protection_domain()`. Finally this all unwraps to: `Staff.java_class.protection_domain` – zipizap Feb 23 '16 at 10:48
0

So there are a couple gotchas here (at least they were for me).

1) You can't get the java Class using the Constant like Staff.class - this will return the ruby Class object.

2) Once you have a java instance, you can only get it's java.lang.Class by using the getClass() method. Calling class with again give you the class object from the ruby hierarchy.

x = Java::java.lang.String.new("hi")
x.class.kind_of?(Java::java.lang.Class)  # evaluates to false
x.getClass().kind_of?(Java::java.lang.Class)  # evaluates to true

so then I just have to have an instance of Staff (in my example in the question) like this:

Staff.new.getClass().getProtectionDomain()
Tony Eichelberger
  • 7,044
  • 7
  • 37
  • 46
  • You can also get the java class without creating a new instance, by using #java_class: `Java::java.lang.String.java_class # => Java::java.lang.String.java_class`. – zipizap Feb 23 '16 at 10:06