有没有办法在Java中动态实现接口?

时间:2013-03-16 11:30:25

标签: java reflection interface

我正在开发一个允许用Lua创建mod的Minecraft mod。我希望用户能够使用他们想要的接口创建TileEntities。目前我使用的是调用已注册Lua文件功能的Base TE,但这不允许他们制作库存和外围设备。

1 个答案:

答案 0 :(得分: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
                      }
                 });