JRuby issues creating Java type cast float array

Viewed 120

I'm using jruby-9.2.6.0 to import a Java pdf library. PDColor is a class that becomes instantiated with an array of floats as well as a string constant. The Java example code that I'm referencing looks like the following:

import org.apache.pdfbox.pdmodel.graphics.color.PDColor;

PDColor componentColor = new PDColor(new float[]{1, 0, 0}, PDDeviceRGB.INSTANCE);

In jruby, my code looks like the following:

import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceRGB;

float_arr = [1.to_f, 0.to_f, 0.to_f]
componentColor = PDColor.new(float_arr, PDDeviceRGB::INSTANCE)

The issue is, it seems that the float_arr param is not typed as a float array, and thus we get the following error:

NameError (no constructor for arguments (org.jruby.RubyArray,org.apache.pdfbox.pdmodel.graphics.color.PDDeviceRGB) on Java::OrgApachePdfboxPdmodelGraphicsColor::PDColor)
  available overloads:
    (org.apache.pdfbox.cos.COSArray,org.apache.pdfbox.pdmodel.graphics.color.PDColorSpace)
    (org.apache.pdfbox.cos.COSName,org.apache.pdfbox.pdmodel.graphics.color.PDColorSpace)
    (float[],org.apache.pdfbox.pdmodel.graphics.color.PDColorSpace)

Is there a known way in jruby to convert a Ruby array of floats into a Java float array?

1 Answers

As mentioned by @TilmanHausherr, the constructor expects a Java array of primitive floats. To create it, you can call Array#to_java(:float).

Here's a small program to test this behavior. pdfbox-2.0.15.jar should be in the same folder as the script, which should be run with jruby:

require './pdfbox-2.0.15.jar'
java_import 'org.apache.pdfbox.pdmodel.graphics.color.PDColor'
java_import 'org.apache.pdfbox.pdmodel.graphics.color.PDDeviceRGB'
red = PDColor.new([1.0, 0, 0].to_java(:float), PDDeviceRGB::INSTANCE)
puts red
#=> PDColor{components=[1.0, 0.0, 0.0], patternName=null}
Related