2013-03-16 125 views
0

我正在开发一个Minecraft mod,允许使用Lua创建Mod。我希望用户能够使用他们想要的接口创建TileEntities。目前,我正在使用调用注册Lua文件功能的Base TE,但这不允许他们制作库存和外围设备。有没有办法在Java中动态实现接口?

+3

这不是完全清楚你在找什么。这可能是反射[代理](http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/reflect/Proxy.html)会解决你的问题? – onon15 2013-03-16 11:34:23

回答

5

是的。您可以通过ClassLoader.html#loadClass(...)加载界面和使用Proxy#newProxyInstance(...)

示例实现:

ClassLoader cl = getClass().getClassLoader(); 
Class<?> desiredInterface = cl.loadClass("SomeInterface"); 
Object proxy = Proxy.newProxyInstance(
       cl, 
       new Class<?>[]{desiredInterface}, 
       new InvocationHandler() { 
         @Override 
         Object invoke(Object proxy, Method method, Object[] args) { 
         //call Lua with method name and args, return answer 
         } 
       }); 
+0

有没有办法让返回的对象扩展另一个类? – Rule 2013-03-16 13:34:28

+0

嗯,是的,但AFAIK不是没有字节码操作。看看http://cglib.sourceforge.net/,http://asm.ow2.org/,http://www.csg.is.titech.ac.jp/~chiba/javassist/,http: //commons.apache.org/proper/commons-bcel//index.html。 – 2013-03-18 09:17:59

相关问题