Can I use wildcards in my "java_import" statements to load into the global namespace? [duplicate]

StackOverflow https://stackoverflow.com/questions/20363226

  •  28-08-2022
  •  | 
  •  

Question

Note: This is not a dupe question! The suggested dupe's answer only works in a module, not the global namespace, so it's not quite the same.

I'm surprised that I can't find a solid answer to this question.

Note that include_package as suggested by this answer is not the solution I am looking for, as it will only let you import a package into a module's namespace. It does not load into the global namespace.

If my JRuby script has something like:

java_import "com.example.shapes.circle"
java_import "com.example.shapes.square"
java_import "com.example.shapes.triangle"

I want to do something like this:

java_import "com.example.shapes.*"

But that's a syntax error, as it appears to try to load "*" as a literal classname and not as a wildcard.

This also doesn't work:

java_import "com.example.shapes"

Is there a way to do this?

Was it helpful?

Solution

The answer appears to be "no". You can't load all of a package's classes into the global namespace. At least, not easily.

A post here appears to describe a way, though it is incredibly ugly. (I got that link from the JRuby Github wiki).

That ugly way looks something like this, but it did not work for me.

module M
  include_package "com.example.shapes"
end

class Object
  class << self
    alias :const_missing_old :const_missing
    def const_missing c
      M.const_get c
    end
  end
end

Circle #should work
Triangle #should work

Again, it didn't work for me, but I might have messed something up. I'm not going to pursue, because I'm not really interested in putting crazy hacks like this in my code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top