Reputation: 188
I have a Response class
which contains n number of fields and there are multiple classes which extend my Response class
. In every method I need to set fields of the response class along with my sub class fields, instead i want to create a common method which sets all the fields of my parent class and returns me the sub class.
Parent Class
class Response{
private String a;
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
}
Sub Class 1
class Custom extends Response{
private String b;
public String getB() {
return b;
}
public void setB(String b) {
this.b = b;
}
}
Sub Class2
class Custom1 extends Response{
private String c;
public String getC() {
return c;
}
public void setC(String c) {
this.c = c;
}
}
method 1
public Custom setFields(String aValue,String bValue){
Custom c = new Custom();
c.setA(aValue);
c.setB(bValue);
return c;
}
method 2
public Custom1 setFields(String aValue,String cValue){
Custom1 c1 = new Custom1();
c1.setA(aValue);
c1.setC(cValue);
return c1;
}
I want to create a method which sets the value of the fields belonging to the Response class and return me the same class object Custom or Custom1 respectively
Ex:
Custom c = setResponseValue(aValue); OR
Custom1 c1 = setResponseValue(aValue);
Methods something like
public Custom/Custom1 setResponseValue(String value){
/**
Sets the value
**/
return Custom/Custom1;
}
Please help as i need to do the same thing over and over again.Problem increase as the no of fields increase in the response class.
Upvotes: 0
Views: 1273
Reputation: 2975
Since you want to return a child class with the value of the parent set, you could have your child class constructor with an input value and use it to set the value on the parent.
public class Response {
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
public class Child extends Response {
public Child(String value) {
setValue(value);
}
}
And then use it like this:
Child childResponse = new Child("hey");
Update: I am not sure I understand exactly what you mean, but if you do not want to set the value in the constructor, and you don't want to set the value for an existing child object, maybe you need a cloned object returned with this new value. Make sure your class supports the Cloneable interface and:
public Child cloneAndSetValue(String value) throws CloneNotSupportedException {
Child c = (Child) this.clone();
c.setValue(value);
return c;
}
Upvotes: 3
Reputation: 5948
If you want setResponseValue
to be outside of your pojo classes then you need to tell it how to create a specific subclass. Here is how you can accomplish it with Java lambdas and generics:
Custom c1 = setResponseValue( Custom::new, "a1" );
Custom1 c2 = setResponseValue( Custom1::new, "a1" );
public static <T extends Response> T setResponseValue(Supplier<T> s, String value){
T result = s.get();
result.setA(value);
return result;
}
Upvotes: 0