luaj-lua中实例化JavaClass

LuaJ提供了LuaJavaLib来方便地实现Lua和Java的混用。

使用luajava在Lua中实例化JavaClass

LuaLogTest.java一个简单的Log示例类

package com.mislead.luaj.java_lua;

public class LuaLogTest {

  public static String TAG = LuaLogTest.class.getSimpleName();

  public static void staticInfo(String msg) {
    System.out.println(String.format("static info: %s", msg));
  }

  public void info(String msg) {
    System.out.println(msg);
  }

  public void error(String msg) {
    System.err.println(msg);
  }
}

test.lua

-- use luajava.newInstace to instace a java class
local luaLog = luajava.newInstance("com.mislead.luaj.java_lua.LuaLogTest")
-- use java class methods
luaLog:info("this is info")
luaLog:error("this is error")

-- use luajava.bindClass to bind a class to lua
-- then use luajava.new to instance it
local LuaLog = luajava.bindClass("com.mislead.luaj.java_lua.LuaLogTest")
-- use static java class method & field
LuaLog:staticInfo("info")
print(LuaLog.TAG)
-- instance class
local newLog = luajava.new(LuaLog)
-- use java class method
newLog:info("this is newLog info")
-- a JFrame example
local jframe = luajava.bindClass("javax.swing.JFrame")
local frame = luajava.newInstance("javax.swing.JFrame", "this is text")
frame:setDefaultCloseOperation(jframe.EXIT_ON_CLOSE)
frame:setSize(300, 400)
frame:setVisible(true)

在Java中使用luajava示例

Globals globals = JsePlatform.debugGlobals();
String currentTime = globals.get("luajava")
    .get("bindClass")
    .call(LuaValue.valueOf("java.lang.System"))
    .invokemethod("currentTimeMillis").toString();
System.out.println(currentTime);
相关文章
相关标签/搜索