简体   繁体   中英

Is there a way in eclipse to to generate a simple class with getters and setters

So basically, I've been making a lot of classes with are simply just containers for some logical information.

Eg class Book; has properties ISBN, Title, Author; has getters and setters for all properties.

I know eclipse can auto generate getters and setters, but a) It doesn't correctly copy property comments onto them, b) it's still quite slow as after typing out all the properties, you have to right click each one and auto generate the comments.

I know it's trivial, but considering I've probably spent more than a few days just doing this over the last few years, it's got me wondering if there's a better option out there.

I'm imagining something like a wizard where you just have a table that you type your properties type, name, and description, and tick if it's allowed to be null, and if it's allowed to be edited, and if you want it to be populated by the constructor, and then you get a class with all the correct comments, validation calls to check for null, and getters and setters.

If not, is there a way I can extend eclipse to do something like this? I could build my own external program, but it seems a little clunky to do it outside, then have to update eclipse each time.

To avoid duplicating documentation (if that is what you are trying to achieve) I use:

/**
 * Represents the book title
 */
private String title;

/**
 * Get {@link #title}
 */
public String getTitle() {
    return title;
};

You can have eclipse auto generate it by using the following comments template:

/**
* Get {@link #${field}} 
*/

You could use http://immutables.github.io/

It is an annotation processor that generate Java classes. You don't need any plugins to run it. It is sufficient to have annotation processing enabled.

You create an abstraction and the lib generates concrete implementation for You. Even corresponding javadoc will be copied to the generated class.

For example You would have to create an interface like below:

import org.immutables.value.Value;
// Define abstract value type
@Value.Immutable
public interface ValueObject {
  String name();
  List<Integer> counts();
  Optional<String> description();
}

And then You instantiate it like this:

// Use generated immutable implementation
ValueObject valueObject =
    ImmutableValueObject.builder()
        .name("My value")
        .addCounts(1)
        .addCounts(2)
        .build();

There are more options available.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM