Java,动态创建界面?

发布于 2024-09-27 13:56:03 字数 216 浏览 1 评论 0原文

我正在寻找一种在运行时创建界面的解决方案。我真的不知道这是否可能。

问题:

我有一个 OSGi 服务,它发布一个 Map,其中键定义了该服务的操作。我想使用 spring 直接将此服务发布为 Hessian 服务,但为此,我需要删除一个接口。现在我想在运行时创建这个界面。

I'm looking for a solution to create an interface in runtime. I don't really know if this is possible in anyway.

Problem:

I've got a OSGi service which publishes a Map<String,String> where the key defines an action for this service. I want to publish this service directly as Hessianservice with spring but for this, I need to delcare an interface. Now I would like to create this interface at runtime.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

何必那么矫情 2024-10-04 13:56:03

可以动态创建接口,例如通过使用字节码操作库(例如 ASM)生成接口。但是不可能使用该接口,因为无法针对它编译任何代码(除非您也动态生成使用它的代码)。

你想做什么?

It's possible to create interfaces dynamically for example by generating it with a bytecode manipulation library such as ASM. But it won't be possible to use that interface, because no code can be compiled against it (unless you generate dynamically also the code which uses it).

What is it that you are trying to do?

殤城〤 2024-10-04 13:56:03

你不能真正做到这一点(除非你涉及字节码操作/创建,并且我认为这不是最好的路径)。

如果没有任何东西可以访问动态创建的接口,那么动态创建的接口有什么用呢?

或者换句话说:没有任何东西可以针对动态创建的接口进行编译(因为显然它在编译时不存在)。那么谁会使用它呢?

You can't really do that (unless you involve byte-code maniuplation/creation and I don't think that's the best path).

What good would a dynamically created interface do if you have nothing that could access that interface?

Or in other words: nothing can compile against a dynamically created interface (since it doesn't exist at compile-time, obviously). So who would be using it?

没企图 2024-10-04 13:56:03

另一个问题中选择了以下答案。该示例实际上编写了一个新类,因此这可能会对您有所帮助。

JDK6 有一个 Java 编译器 API。然而,它并不一定很容易使用。

谷歌很快就找到了这个示例用法

Picked the following answer from another question. The example actually writes a new class, so may be this will help you.

JDK6 has a Java compiler API. However, it's not necessarily very easy to use.

A quick google pulled up this example usage.

可是我不能没有你 2024-10-04 13:56:03

接口和类的存在只是为了帮助编译器发现可能的错误。如果你想在运行时制作这个接口,你没有编译器,它不会发现你的错误,那么你为什么需要这个接口呢?

在这种情况下,只需发布​​一些通用接口的实现,如下所示:
接口 通用接口 {
对象 invokeMethod(字符串名称, 对象...参数);
}
这是您需要的唯一接口,您可以在编译时创建它!仅您可能需要在运行时创建它的实现,例如使用 java.lang.reflect.Proxy

Interfaces and classes exist solely to help compilers find possible bugs. If you want to make this interface at runtime, you have no compiler, co it won't find you the bugs, so why do you need this interface?

In such a situation just publish implementation of some generic interface, which can look like:
interface GenericInterface {
Object invokeMethod(String name, Object... arguments);
}
That's the only interface you need, and you can create it at compile time! Only implementations of it you may need to create at runtime, eg with java.lang.reflect.Proxy

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文