2013-03-16 122 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

相關問題