java运行时的方法声明
我尝试在运行时为一个类声明一个java方法。我不应该在编译时编写该方法或对其进行硬编码。我认为有某种方法可以使用反射,但我不知道如何使用。怎么会发生这种事呢?
这一切从何而来: 我会阅读输入内容;
name=john,age=21
name=smith,age=23
然后我必须使用“getname”和“getage”方法访问他们所有的“name”和“age”值。
但是姓名和年龄单词可以更改为 ie。姓氏和长度;然后我必须使用“getsurname”和“getlength”方法访问他们的姓氏和长度。
我知道我会使用invoke来调用getXXX方法。但是我如何在运行时声明它们呢? 这才是真正的问题。
I try to declare a java method for a class in run time. I should not write the method in compile time or hard-code it. There is some way using reflection, I think but I cannot figure out how. How can this happen?
What all this came from:
I will read the input like;
name=john,age=21
name=smith,age=23
then I have to access all their "name"s and "age"s values with a method of "getname" and "getage".
However the name and age words can be changed to ie. surname and length; then I have to access their surname and length with the methods of "getsurname" and "getlength".
I know that I will use invoke to call getXXX methods. But how can I declare them during runtime?
That is the actual problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用字节码生成库(如 ASM)、代码片段库(如 BeanShell)或使用 Compiler API 在运行时编译类。
但是,我也怀疑您不需要这样做,并且有一种更简单的方法。也许你可以说出你想要这个方法做什么?
You can use a byte code generation library like ASM, code snipplet library like BeanShell, or use the Compiler API to compile the class at runtime.
However, I also suspect you don't need to do this, and there is a much easier way. Perhaps you can say what you want this method to do?
Reflection 并不意味着向类添加新方法。 Peter 提到了一些高级工具可以帮助您完成此任务。
Reflection is not meant to add new methods to a class. There are some advanced tools Peter mentioned which may help you accomplish this.
我假设您可能能够使用 代理类 并且可能是用 Java 编写或可以与 Java 交互的脚本语言解释器(例如 Rhino)。如果您设法将其与 Rhino 集成,您可能必须用 Javascript 编写该方法,但您仍然可以从中访问您可能需要的任何 Java 对象。
I would assume you might be able to use proxy classes and possibly a scripting language interpreter that is either written in or can interface with Java (e.g. Rhino). If you manage to integrate it with Rhino you'd probably have to write the method in Javascript but you can still access whatever Java objects you might need from it.