Restrict Lua Object-access to an interface.

13 views
Skip to first unread message

Marvin Löbel

unread,
Jun 2, 2012, 6:28:46 AM6/2/12
to JNLua Discussion
Hi, I stumbled upon a small problem while using jnlua for a hobby
project:

In a java function, I'm pushing a java object into a lua state.
In the function, the object is declared as an interface, that is only
a subset of its members are accessible at that point.
However, when I push it to the lua side the object instance itself is
made available there, that is all its members can be accessed.

Is this due to how jnlua implements the java-lua mapping, or a
limitation of the java reflection API (with which I have no
experience)?
Is there a way to solve this problem?

Thanks,
Marvin

Andre Naef

unread,
Jun 3, 2012, 11:33:05 AM6/3/12
to jnlua-...@googlegroups.com
In the Java function, the interface type is really only a type declaration,
and nothing prevents you from casting the object with that interface type
declaration back to its implementing class, thus making all methods
accessible. Now, as you pass the object to Lua, there is no interface type
declaration as Lua is dynamically typed, and all methods of the object are
thus accessible by default. To phrase this another way, when you pass an
object to Lua, you are passing that object with its dynamic type information
only, and all static type information, such as an interface type declaration
in the formal parameter list of a method, is gone.

How to solve this? For most cases, you may simply be able to live with it.
Any Lua code that uses more than the interface you are promising on the
object is simply bound the break at some point. If for some reason you
really have to restrict the access, one way to achieve this is to pass a
wrapper object that only exposes the interface methods you want to expose.
This could be implemented with an anonymous interface instantiation like
this:

final Object o;
luaState.pushObject(new Interface() {
void foo (int a) {
o.foo(a);
}

int bar() {
return o.bar();
}
});

Marvin Löbel

unread,
Jun 3, 2012, 2:29:42 PM6/3/12
to jnlua-...@googlegroups.com
Thank you, I didn't quite realize that you can circumvent the interface restriction on java side like that. This makes my problem a moot point, as what I'm trying to do doesn't work anyway. ;)
Back to design phase I guess...
Reply all
Reply to author
Forward
0 new messages