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

折月煮酒 提交于 2019-12-12 02:59:59

问题


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:


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.



来源:https://stackoverflow.com/questions/35391769/luaj-how-to-create-instance-of-java-object-in-lua-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!