首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >LuaJ数组/列表类型安全

LuaJ数组/列表类型安全
EN

Stack Overflow用户
提问于 2016-06-24 02:44:36
回答 1查看 1.2K关注 0票数 4

所以使用LuaJ。

如果我传递一个用户数据List<T> (类型为T ),从Java到Lua,Luaj仍然允许通过:add函数插入任何类型对象的数组。例如:

Java代码:

代码语言:javascript
复制
import java.util.ArrayList;
import org.luaj.vm2.Globals;
import org.luaj.vm2.lib.jse.CoerceJavaToLua;
import org.luaj.vm2.lib.jse.JsePlatform;
import org.luaj.vm2.LuaValue;

ArrayList<Integer>ExampleList=new ArrayList<>();
ExampleList.add(1);
LuaValue[] LuaParams=new LuaValue[] {
    CoerceJavaToLua.coerce(ExampleList)
};

Globals globals=JsePlatform.standardGlobals();
try { globals.get("TestFunc").invoke(LuaValue.varargsOf(LuaParams)); }
catch(Exception e) {}

卢阿:

代码语言:javascript
复制
function TestFunc(arr)
    arr:add("str")
    arr:add(2);
end

ExampleList的结果:

代码语言:javascript
复制
{
    new Integer(1),
    new String("str"), //This should not be allowed!
    new Integer(2)
}

由于ExampleList是一个List<Integer>,所以不应该允许该字符串。

问:有什么方法来维护类型安全吗?

如果这有助于测试,下面是将lua脚本添加到lua内存中的代码(就在try{}之前):

代码语言:javascript
复制
globals.load(
    "function TestFunc(arr)\n"+
    "        arr:add(\"str\")\n"+
    "        arr:add(2);\n"+
    "end",
"ExampleScript").call();
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-07-06 05:05:35

在进行了研究之后,我发现不可能找到数组声明为什么泛型类型。Java不将该信息存储在对象中。在运行时,它只使用数组声明的类型作为当前变量引用。

你所能做的就是看看它里面的对象来确定它应该是什么,但这并不是万无一失的。

如果数组是在另一个对象中定义的,那么您可以查看父对象的字段以获得数组的组件/模板/泛型类型。

ArrayList reflection

在2016-07-06年的编辑中,我所知道的另一个建议方法是用一个接口扩展所有的列表类,这个接口实际上存储了类的类型。不过,这对这个项目来说并不太实际。考虑过之后,Java为什么不为列表存储泛型类类型,这是有意义的。

我最后使用的解决方案是使用以下内容编辑org.luaj.vm2.lib.jse.JavaMethod.invokeMethod(Object instance, Varargs args) (在Object[] a = convertArgs(args);行之后):

代码语言:javascript
复制
//If this is adding/setting to a list, make sure the object type matches the list's 0th object type
java.util.List TheInstanceList;
if(
    instance instanceof java.util.List && //Object is a list
    java.util.Arrays.asList("add", "set").contains(method.getName()) && //Adding/setting to list
    (TheInstanceList=(java.util.List)instance).size()>0 && //List already has at least 1 item
    !a[a.length>1 ? 1 : 0].getClass().isInstance(TheInstanceList.get(0)) //New item does not match type of item #0
)
    return LuaValue.error(String.format(
            "list coercion error: %s is not instanceof %s",
            a[a.length>1 ? 1 : 0].getClass().getName(),
            TheInstanceList.get(0).getClass().getName()
    ));

虽然可以通过遍历两个对象的扩展父类型列表(在java.lang.Object之前的所有内容)来考虑匹配父类,但就类型安全性而言,这将不像我们需要的项目那样安全。

我从上面使用的解决方案是专门用于清除LUA脚本中的错误,然后再投入到生产中。

我们还可能需要进行黑客攻击,其中某些类在比较时被认为是它们的祖先或继承类之一。

编辑在2016-07-08我最终添加了列表的能力,并声明了一个类型,所以没有类型猜测的必要。

从上面替换代码块的代码:

代码语言:javascript
复制
//If this is adding/setting to a list, make sure the object has the proper class type
if(
    instance instanceof java.util.List && //Object is a list
    java.util.Arrays.asList("add", "set").contains(method.getName()) //Adding/setting to list
) {
    //If this is a TypedList, use its stored class for the typecheck
    java.util.List TheInstanceList=(java.util.List)instance;
    Class ClassInstance=null;
    if(instance instanceof lua.TypedList)
        ClassInstance=((lua.TypedList)instance).GetListClass();
    //Otherwise, check for a 0th object to typecheck against
    else if(TheInstanceList.size()>0) //List already has at least 1 item
        ClassInstance=TheInstanceList.get(0).getClass(); //Class of the 0th item

    //Check if new item does not match found class type
    if(
        ClassInstance!=null && //Only check if there is a class to check against
        !ClassInstance.isInstance(a[a.length>1 ? 1 : 0]) //Check the last parameter's class
    )
        return LuaValue.error(String.format(
                "list coercion error: %s is not instanceof %s",
                a[a.length>1 ? 1 : 0].getClass().getName(),
                ClassInstance.getName()
        ));
}

以及TypedList的代码:

代码语言:javascript
复制
/**
 * This is a special List class used with LUA which tells LUA what the types of objects in its list must be instances of.
 * Otherwise, when updating a list in LUA, whatever is the first object in a list is what all other objects must be an instance of.
 */
public interface TypedList {
    Class GetListClass();
}

裸ArrayList作为TypeList:

代码语言:javascript
复制
import java.util.ArrayList;

public class TypedArrayList<E> extends ArrayList<E> implements TypedList {
    private Class ListType;
    public TypedArrayList(Class c) {
        DefaultConstructor(c);
    };
    public TypedArrayList(Class c, java.util.Collection<? extends E> collection) {
        super(collection);
        DefaultConstructor(c);
    }
    private void DefaultConstructor(Class c) { ListType=c; }
    @Override public Class GetListClass() {
        return ListType;
    }
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38004865

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档