I have two classes with identical implementations but different names. They are generated and I'm not able to modify them:
public class Foo {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Bar {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
I need to populate these classes with data, and since they are identical would prefer to do it with a single class or reference, then cast to (or hopefully the solution is more elegant) the Foo or Bar as needed. Conceptually:
FooOrBar fob = ????;
fob.setName("XYZ");
Foo f = fob.(???);
Bar b = fob.(???);
I've looked into generics, but it appears that is for when you truly don't know what Class you will be operating on. Is it possible for me to have some type of Class or reference that achieves this?
July 26 EDIT:
Apologies if it's bad form for follow ups like this, I can post new if need be. I'm in the process of implementing Tomasz's Adapter pattern but my final step differs from his. I have a need for conditional assignment of the interface object. The below is what I have and I get no errors or warnings on it so far, but I'm wondering if this isn't good practice for some reason? Perhaps I should use reflection or generics to determine the class for the interface? This will be in a method that only my code will call and I will know the condition. I've searched on conditional interface assignment but haven't found much.
FooOrBar fob; //interface
if (condition true) {
fob = new FooAdapter(); //FooAdapter implements FooOrBar
} else {
fob = new BarAdapter(); //BarAdapter implements FooOrBar
}
fob.setName("XYZ");