yamachan
yamachan

Reputation: 1079

I'd like to set and get instance properties with methods in a class

I am a beginner of Java. I have a question.

Foo.java

public class Foo {
    private String name;
    private int num;

    Foo(String name, int num) {
        this.name = name;
        this.num = num;
    }

    public String getName() {
        return this.name;
    }

    public int getNum() {
        return this.num;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setNum(int num) {
        this.num = num;
    }

}

Main.java

public class Main {
    public static void main(String[] args) {
        String name = "Tom";
        int num = 60;
        Foo bar = new Foo(name, num);
    }
}

Instead of this typical style of class on Java, I'd like to set and get instance properties with getter() and setter() method like...

public void setter(String p) {
    this.p = p;
}

public String getter(String q) {
    return this.q
} 

I know these don't work, but I want to write Java method like following these codes in Python.

setattr(self, key, val)
getattr(self, key)

Would you please give me some pieces of advices?

Upvotes: 3

Views: 2310

Answers (2)

byxor
byxor

Reputation: 6379

Java does not support properties.

The only way to do this is through accessor and mutator (get/set) methods like you did at the top.

See: does java have something similar to C# properties?

Upvotes: 4

Nicolas Filotto
Nicolas Filotto

Reputation: 45005

What you want to achieve can be done using reflection as next:

// get the field "key" from the class "Foo"
Field field = Foo.class.getField("key");
// make it accessible as it is a private field
field.setAccessible(true);
// set the value of this field to val on the instance self
field.set(self, val);

More details about reflection here

Upvotes: 1

Related Questions