如何注入方法的返回值?
我什至不确定这是否可能,但由于这个问题,我提出了这个想法: 使用 Java 反射更改私有静态最终字段
所以这是场景:
public static String test() {
return "test test test";
}
我想要做的就是让 test() 方法返回“worked”而不是“test test test”。 有谁知道如何实现这一点?
编辑:
我下载了 powermock 并尝试了这个:
package test;
导入 org.powermock.api.easymock.PowerMock;
公共类 InjectorTest {
public static void main(final String[] args) { System.out.println("Before the injection:"); System.out.println(test()); PowerMock.mockStatic(InjectorTest.class); PowerMock.doReturn("worked").when(InjectorTest.class, "test"); System.out.println("After the injection:"); System.out.println(test()); } public static String test() { return "did not work :("; }
}
但是 Eclipse 给出了这个错误: The method doReturn(String) is undefined for the type PowerMock
我是否下载了错误的代码,或者是一个错误的示例代码?
因为我不想获得更多投票,为什么我要这样做?
我想以不使用 user.home 而是相对 URI 的方式注入 Minecraft。
通过这种方式,我可以为学校制作一个预装的便携式 Minecraft(我的世界),用于 U 盘:D
I am not even sure if this is possible, but I came up with this idea because of this question: Change private static final field using Java reflection
So this is the scenario:
public static String test() {
return "test test test";
}
What I want to do this let the test() method return "worked" instead of "test test test".
Does anybody have an idea how to accomplish this?
EDIT:
I downloaded powermock and tried this:
package test;
import org.powermock.api.easymock.PowerMock;
public class InjectorTest {
public static void main(final String[] args) { System.out.println("Before the injection:"); System.out.println(test()); PowerMock.mockStatic(InjectorTest.class); PowerMock.doReturn("worked").when(InjectorTest.class, "test"); System.out.println("After the injection:"); System.out.println(test()); } public static String test() { return "did not work :("; }
}
But eclipse gives this error: The method doReturn(String) is undefined for the type PowerMock
Did I download the wrong one or was that a bad sample code?Because I don't want more votedowns, WHY I want to do this?
I want to inject Minecraft in that way that it doesn't uses the user.home but a relative URI.
In this way I can make a pre-installed portable Minecraft for an USB stick for school :D
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为 PowerMock 可以做到这一点。 (Java 反射在幕后)
使用 PowerMock,您的代码将如下所示:
上面的代码归功于 @RC
I think PowerMock can do this. (Java reflection under the hood)
With PowerMock, your code would look like this:
Credits to @RC for code above