Skip to content
Advertisement

how to auto-fill an object in java?

i have a simple pojo

class animal{

private String name;

animal(String name){
 this.name = name;}

private Features features;

private int max_life;

//
*
* other properties and their getter's and setter's
*//
}

so now once i initialize the name of the POJO with any name i want the rest of the attributes to auto fill.

eg: animal("cat") should auto-fill other attributes such as max_life and features based on a cat.

is there any property’s file or any way that will detect the initialization and auto fill them with pre-defined properties??

Advertisement

Answer

I can actually think of several ways to implement such thing. But what you’re looking for is a factory.

The idea is: the factory receives the animal kind, and creates the instance based on the kind.

In general, the most basic (although terrible) example is:

public class AnimalFactory {
    public Animal create(String name) {
        if (name.equals(“cat”)) {
            return new Animal(...);
        }
    // other
    }
}

You may then create animals as such:

AnimalFactory factory = new AnimalFactory();
Animal kitty = factory.create(“cat”);

This can be done in multiple ways and improved in many aspects. Read more about the Factory design pattern.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement