Víctor Cima Granda Víctor Cima Granda - 13 days ago 5
Java Question

How to change, inside a class, the value of an attribute in runtime?

I have the following structure, where there is an abstract class with a baseDirectory attribute by default.

public abstract class PerformanceTest {
/**
* Base directory.
*/
private String baseDirectory = "C:/msg-inbox/";


...

On the other hand there is a class that extends from the abstract class.

public class MessagePerformanceTest extends PerformanceTest {
/**
* Constructor.
*/
public MessagePerformanceTest() {
}


...

Finally I have a main class like this:

public class MessagesMain {

public static void main(String[] args) {

Field field = PerformanceTest.class.getDeclaredField("baseDirectory");
field.setAccessible(true);
field.set(null,args[0]);

MessagePerformanceTest messagePerformanceTest = new MessagePerformanceTest();
messagePerformanceTest.createMessages();


...

The problem that i am facing is that i dont know the best way to pass de baseDirectory attribute as an argument because I need to change this value in runtime. I´m trying to use reflection but its not working by the moment. Have anyone idea about a possible workaround?

To sum up I need to change de default value C:/msg-inbox/ to another thing similar to \folder1\test

Regards

Answer

baseDirectory is an instance field, meaning it belongs to an instance of PerformanceTest. So to change its value you need an instance of PerformanceTest.

But PerformanceTest is abstract class so you cant have its instance. Lucky you have its base class MessagePerformanceTest to create instance of type PerformanceTest. You need something like this: note: I have created get() method to check the changed value.

public abstract class PerformanceTest {
/**
* Base directory.
*/
private String baseDirectory = "C:/msg-inbox/";

    public String get(){
        return baseDirectory;
    }
}

 public class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(new MessagePerformanceTest().get() );
          Field field = PerformanceTest.class.getDeclaredField("baseDirectory");
          field.setAccessible(true);
          MessagePerformanceTest  mpt = new MessagePerformanceTest ();
          field.set( mpt," \folder1\test");
          System.out.println(mpt.get() );
    }

}

mpt is an instance of MessagePerformanceTest and hence instance of type PerformanceTest