classreflectionjruby

Get Java Class represented by a String in JRuby? (without eval)


I want to call a static method on a Java Class in JRuby. Presently to acheive this I use:

class_name = "com.slackworks.naether.util.LogUtil"
clazz = eval(class_name)
clazz.setLogLevel( "debug" )

It seems clumsy to have to use an eval to convert the String into a Class. I have look around but cannot find a JRuby helper to take place of the eval.


The reason I need a String to converted to a Class is this is happening in a wrapper that handles requests over JRuby or RJB, depending on the Ruby runtime. If the Ruby runtime uses RJB, the call would resemble:

class_name = "com.slackworks.naether.util.LogUtil"
clazz = Rjb::import( class_name )
clazz.setLogLevel( "debug" )

Solution

  • If you want to load/get a proxy class without actually hooking it into your namespace you can use:

    str_class = JavaUtilities.get_proxy_class("java.lang.String")
    

    Please be aware: this is only useful in certain situations, use normal java_import if possible.