您还可以使用等效的语法:
obj.test(obj)
这是一样的
obj:test()
您应该能够获取 Java 类或实例的任何字段或方法,但在某些情况下需要额外的参数,而冒号语法是一种方便的快捷方式。
为了说明,构造一个具有各种静态和实例字段和方法的类,例如:
public static class MyClass {
public static String variable = "variable-value";
public String field = "field-value";
public static String func() {
return "function-result";
}
public String method() {
return "method-result";
}
如果您像示例中那样强制该类的实例,则以下是访问每个实例的语法:
Globals globals = JsePlatform.standardGlobals();
// Load an instance into globals
LuaValue instance = CoerceJavaToLua.coerce(new MyClass());
globals.set("obj", instance);
LuaValue chunk = globals.load(
"print( obj );" +
"print( obj.variable );" +
"print( obj.field );" +
"print( obj.func );" +
"print( obj.method );" +
"print( obj:method() );" + // same as 'obj.method(obj)'
"print( obj.method(obj) );");
chunk.call();
这对我来说产生了
Example$MyClass@4554617c
variable-value
field-value
function: JavaMethod
function: JavaMethod
method-result
method-result
您可能还想强制上课。除了类不存在的字段之外,仍然可以访问所有内容:
// Load a class into globals, 'field' cannot be accessed
LuaValue cls = CoerceJavaToLua.coerce(MyClass.class);
globals.set("cls", cls);
chunk = globals.load(
"print( cls );" +
"print( cls.variable );" +
"print( cls.func );" +
"print( cls:func() );" + // same as 'cls.method(cls)'
"print( cls.func(cls) );" +
"print( cls.method );" +
"print( cls.method(obj) );");
chunk.call();
输出是:
class Example$MyClass
variable-value
function: JavaMethod
function-result
function-result
function: JavaMethod
method-result
在 lua 中,可以通过“new”从 Java 类构造一个实例,然后它的行为类似于其他 Java 实例:
// Construct an instance from a class using 'new'
chunk = globals.load(
"print( cls.new );" +
"print( cls.new() );" +
"print( cls.new().field );"); // etc.
chunk.call();
输出是
function: JavaConstructor
Example$MyClass@4b67cf4d
field-value