简体   繁体   中英

JRuby equivalent for casting null to class

I try to use the Java weka machine learning lib through JRuby. It works fine so far, there is only one thing I'm wondering:

In order to create a string Attribute, you can use the same contructor as for nominal Attributes in Java, but with the second parameter being a null casted to FastVector:

Attribute attribute = new Attribute("name", (FastVector) null);

Also see this Stackoverflow post and the weka doc for Attribute .

In JRuby, if you try to pass just nil , eg:

java_import 'weka.core.Attribute'
attribute = Attribute.new('name', nil)

it will raise a Java::JavaLang::NullPointerException error.

The full stack trace is:

Java::JavaLang::NullPointerException: 
from weka.core.Attribute.<init>(weka/core/Attribute.java:303)
from weka.core.Attribute.<init>(weka/core/Attribute.java:290)
from java.lang.reflect.Constructor.newInstance(java/lang/reflect/Constructor.java:423)
from RUBY.<eval>((irb):7)
from org.jruby.RubyKernel.eval(org/jruby/RubyKernel.java:978)
from org.jruby.RubyKernel.loop(org/jruby/RubyKernel.java:1291)
from org.jruby.RubyKernel.catch(org/jruby/RubyKernel.java:1098)
from org.jruby.RubyKernel.catch(org/jruby/RubyKernel.java:1098)
from Users.pgoetze.$_dot_rvm.rubies.jruby_minus_9_dot_0_dot_1_dot_0.bin.irb.<top>(/Users/pgoetze/.rvm/rubies/jruby-9.0.1.0/bin/irb:13)
from java.lang.invoke.MethodHandle.invokeWithArguments(java/lang/invoke/MethodHandle.java:627)

Is there a way to create a null vector in JRuby, that can be passed as the second argument instead of the nil ?

If not, what might be the way to create a string Attribute?

As JRuby wiki states you are supposed to use reflection to obtain a reference to a constructor specifying types of its arguments.

java_import java.util.List
java_import weka.core.Attribute
#...
constructor = Attribute.java_class.declared_constructor(java.lang.String, java.util.List)
attribute = constructor.new_instance('name', nil)

Notes:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM