bjar-bjar
bjar-bjar

Reputation: 707

JAVA: Setting member data at creation, without using constructor

I'm working with som generated classes which I need to set the member data of at creation. The generated classes only have a default constructor, and no setters for the member data. It doesn't make sence to modify the classes, as the modification will be overwritten, when I regenerate the classes again (It's a shared project, so somebady else might also overwrite the generated classes).

Is it possible to do something like this.

Example:

public class A{
    private int value;
}

public class B{
    private A a;
    public void initA()
    {
        a = new A(){
            value = 9;
        };
    }
}

Upvotes: 1

Views: 87

Answers (3)

Jamie Cockburn
Jamie Cockburn

Reputation: 7555

Something like this will allow you to set the value of the private field A.value:

class A {
    private int value;

    @Override
    public String toString() {
        return "Value of my private field: " + value;
    }
}

class MutableA {
    public A a;
    private Field value;

    public MutableA(A a) {
        this.a = a;
        try {
            this.value = A.class.getDeclaredField("value");
        } catch (NoSuchFieldException | SecurityException e) {
            e.printStackTrace();
        }
        this.value.setAccessible(true);
    }

    void setValue(int value) {
        try {
            this.value.set(a, value);
        } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

You can use it like this:

public class Test{
    public static void main(String[] args) {
        A a = new A();
        System.out.println("before mutation:" + a);

        MutableA mutableA = new MutableA(a);
        mutableA.setValue(1);
        System.out.println("before mutation: " + a);
    }
}

Output:

before mutation: Value of my private field: 0
before mutation: Value of my private field: 1

Upvotes: 3

Aniket
Aniket

Reputation: 173

public class A{
    private int value;
   static{
       value=10;
  }
}

public class B{
    private A a;
    public void initA()
    {
        a = new A();
    }
}

Upvotes: 0

user1907906
user1907906

Reputation:

If you only have no argument constructors you will have to use setters to set private members.

Upvotes: 0

Related Questions