Question

In C#, I Can use a simple way like below

public class Dummy 
{
   public string Name { get; set; }
}

but if i use java to do the same thing, i must do like below

public class Dummy {
    private String _name;

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

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

so, you can tell that is at least 7 line codes take the same efftects as 1 line code in c#; so, i'm wondering at is there a simple way in java that i can use to simple set field or get field?

thx for advanced

Was it helpful?

Solution 2

There's nothing built-in to the language, but you could always use Project Lombok's annotation set to generate getters and setters for you at compile-time.

In particular, @Data is quite powerful - it generates your getter, setter, and a toString() method.

Here's an example:

import lombok.Data;

@Data
public class Node<T extends Comparable<T>> {

    private final T data;
    private Node<T> left = null;
    private Node<T> right = null;

    public Node(final T theData) {
        data = theData;
    }

    public void add(final Node<T> theNode) {
        if(data.compareTo(theNode.getData()) <= 0) {
            // goes to the left
            left = theNode;
        } else {
            // goes to the right
            right = theNode;
        }
    }
}

You may have to install a plugin for your IDE to recognize that this is being generated at compile-time, but this takes care of all of your setter and getter boilerplate code.

OTHER TIPS

Java does not support that particular C# idiom, however many IDEs include methods to generate accessors and mutators; for example, in eclipse you can select

Source, Generate Getters and Setters

or

SHIFT-ALT-s   r

That's is language specific, you cannot expect any more.
There is a simpler way to create get/set just by some clicking:
On eclipse editor, right click to open menu\Source\Generate Getters and Setters
-> select property that's you want to getter and setter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top