在Java中注入类字段
大家好 我有一个软件,我想运行多次不同的时间,每次都针对在类的构造函数中设置的类字段的特定值。
例如,代码中的某处类似于
public class Stuff
{
private double importantVal;
public Stuff(double val)
{
this.importantval = val;
}
public double doStuff()
{
return 4 * importantVal;
}
}
此类和方法在程序/调用堆栈中的位置非常靠下,因此我不能仅自行多次调用 doStuff。
我想测试程序的 importantVal 的各种值,也许可以将它们放在文件中并迭代它们。我多次计算出运行程序的简单部分,但我不知道如何替换 importantVal 的不同值。如果一切都失败了,我总是可以编写一个修改源代码的脚本,但这感觉很丑陋而且是临时的。是否有更优雅的解决方案涉及注入,或者类似的东西?
Hello all
I have a piece of software that I would like to run many different times, each for a particular value of a class field that is set in the class's constructor.
E.g, somewhere in the code is something along the lines of
public class Stuff
{
private double importantVal;
public Stuff(double val)
{
this.importantval = val;
}
public double doStuff()
{
return 4 * importantVal;
}
}
This class and method is very far down in the program/call-stack, so I can't merely call doStuff several times by itself.
I would like to test the program for various values of importantVal, perhaps by placing them in a file and iterating over them. I worked out the easy bit of running the program many times , but I have no good idea of how to substitute different values of importantVal. If all else fails I can always write a script that modifies the source code, but that feels ugly and ad-hoc. Is there a more elegant solution involving injection, or something along those lines?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为了说明人们在这里试图告诉您的内容,测试用例如下所示:-
To illustrate what the folks are trying to tell you here, here's how the testcases might look like:-
你有Stuff类的多个实例吗?如果没有,也许您可以尝试通过使 importantVal 静态来“注入”值?或者使用列表注入多个值?
do you have multiple instances of the Stuff class? if not, perhaps you could try "injecting" the values by making importantVal static? or to inject multiple values use a List?