-1

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

Community
  • 1
  • 1
BronzeByte
  • 685
  • 1
  • 7
  • 11
  • 3
    Why would you want to do that? – Mat Nov 26 '11 at 14:05
  • 1
    You should elaborate a little more, why do you want to do that, in what context, ... –  Nov 26 '11 at 14:05
  • 2
    The question you quote is a completely different matter - it deals with changing the value of a _field_, what you are asking is to change the value returned from a method. I don't think it can be done with reflection, but it should be possible with byte code manipulation. Again, why??? why do you want to do such a thing? Just overwrite the method. – Óscar López Nov 26 '11 at 14:09

1 Answers1

3

I think PowerMock can do this. (Java reflection under the hood)

With PowerMock, your code would look like this:

public static void main(String[] args) {
    PowerMock.mockStatic(Foo.class); 
    PowerMock.doReturn("worked").when(Foo.class, "test");
    System.out.println(Foo.test());
}

Credits to @RC for code above

Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
Ajay George
  • 11,759
  • 1
  • 40
  • 48
  • 3
    I can confirm `PowerMock.mockStatic(Foo.class); PowerMock.doReturn("worked").when(Foo.class, "test");` –  Nov 26 '11 at 14:08