如何创建动态IF语句?反射?
是否可以通过反射创建动态 IF 语句?
我看过 BeanShell 的示例(如下所示: 动态 if 语句评估问题字符串比较),但我想知道是否可以在没有 BeanShell 的情况下完成此操作,并指出一些示例以适应我的需求。
基本上我有一个以下形式的语句:A运算符B。A
和B可以是数字(双精度数或整数)或字符串,但A始终与B的类型相同。 运算符可以是 !=、==、>=、>、<=、<,甚至其他可以通过自己的类定义行为的运算符,这是我使用反射的另一个原因,因为我可以采取该字符串并使用反射来调用适当的方法。
我希望(必须)避免分支“if”和“switch”,因为变化太多,并且会随着用户生成的输入而不断变化。
Is it possible with reflection to create a dynamic IF statement?
I have seen examples with BeanShell (like this: Dynamic if statement evaluation problem with string comparison) but i would like to know if it was possible to do it without BeanShell, and be pointed to some examples to adapt to my needs.
Basically i have a statement of the form: A operator B.
A and B can be numbers (Doubles or ints) or strings, but always A is the same type as B.
operator can be !=, ==, >=, >, <= ,<, and even others which behavior may be defined trough a class of their own, another reason why i will use reflection, since i can take that string and use reflection to invoke the appropriate method.
I want (must) to avoid branching "if" and "switch" because the variations are too many and will change constantly with user generated input.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以创建一个工厂,为给定的输入返回正确的运算符。
然后使用它:
You can create a factory that returns the correct operator for the given input.
And then use it:
反思是没有帮助的。反射为您提供有关代码结构(类、方法、属性)的信息,但它不允许您更改和更新现有代码。
不要尝试生成新代码,而是尝试添加一种方式让用户根据他们的输入更改应用程序的行为。
我不知道你到底想做什么。发布一些用户输入和预期行为的示例,以帮助缩小选项范围。但这里有一些事情可能会帮助您完成任务:
Reflection won't help. Reflection gives you information about your code structure (classes, methods, attributes), but it doesn't allow you to change and update existing code.
Don't try to generate new code, try instead of adding a way for users to change the behaviour of your app depending on their input.
I don't know exactly what you are trying to do. Post some examples of user input and expected behaviour to help narrow the options down. But here is a few things that might help you in your task:
您可以创建一个像这样的接口
然后您可以创建多少个您想要的类都实现这样的接口
并像这样加载它们:
您可以准备所有可用运算符的列表并迭代它,甚至配置运算符列表在属性文件上。
You could make a interface like this
Then you could make how many classes you want all implementing the interface like this
and load them like this:
you could so prepare a list of all available operators and iterate over it and even have the list of operators configured on a properties file.