LuaJ How to create instance of Java object in Lua script?

2.1k Views Asked by At

I have Java class:

class SomeClass{
 private int i;
 public SomeClass(int i){
  this.i = i;
 }
}

And I need to create instance of this class in Lua script and pass it to Java function, using LuaJ library. How I can do it?

1

There are 1 best solutions below

0
On BEST ANSWER

This is some example code found on lua.org:

jframe = luajava.bindClass( "javax.swing.JFrame" )
frame = luajava.newInstance( "javax.swing.JFrame", "Texts" );
frame:setDefaultCloseOperation(jframe.EXIT_ON_CLOSE)
frame:setSize(300,400)
frame:setVisible(true)

source: http://www.luaj.org/luaj/3.0/README.html#luajava

With your example, this should translate to:

local obj = luajava.newInstance("your.package.SomeClass",123)
print(obj.i) --> nil -- Since it's a private field

If you have a method public int getValue(), you can use obj:getValue().

I've tested this myself just now, as I hadn't for a long time.