【问题标题】:Is there a way to dynamicly implement interfaces in Java?有没有办法在Java中动态实现接口?
【发布时间】:2013-03-16 11:30:24
【问题描述】:

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

【问题讨论】:

  • 您在寻找什么并不完全清楚。可能是 proxy 的反射会解决您的问题?

标签: java reflection interface


【解决方案1】:

是的。可以通过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
                      }
                 });

【讨论】:

猜你喜欢
  • 2011-02-10
  • 2011-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多