I have the following problem:

A framework generates a class from DB table, each table column is class variable(field). The generated class has more than 30 fields and just one constructor with no parameters.

To create an instance of that class, I have to use 30 times some setters, which is invitation for inconsistencies.

I cannot use directly constructors with parameters or Builder pattern, as I cannot edit the generated class. What's the best way to approach this - Wrapper class, thread safe methods, a classic pattern?

有帮助吗?

解决方案

I have solved this problem for myself by making a BeanBuilder class that uses reflection on the inside. You give it your bean and then call methods like startBean, value and similar to fill your bean with data, much like building an XML tree.

If you are in love with type safety, you can make a similar class for yourself that works specifically with that bean that you have.

其他提示

You can create an external Builder class, that initialises all the fields to some default value whenever you create a new Object, and then behaves like a standard Builder.

You can use Builder pattern. For instance, if you have Car object with field power,weight,maxSpeed,color then you can use Builder like this:

CarBuilder{
private Car car = new Car();

public CarBuilder(int power,int weight){
car.setPower(power);
car.setWeight(weight);
}

public CarBuilder setColor(String color){
car.setColor(color);
return this;
}

public CarBuilder setMaxSpeed(int maxSpeed){
car.setMaxSpeed(maxSpeed);
return this;
}

public Car build(){
return car;
}
}

You can set mandatory fields in costructor and additional fields in settters. Also you can perform some checks in build method.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top