Creating Method that returns a casted object type
Ok, I am attempting to do something a bit odd. Let's say I have the following classes:
Class Super:
Code java:
public class Super {
...
}
Class SubA:
Code java:
public class SubA extends Super {
...
}
Class SubB:
Code java:
public class SubB extends Super {
...
}
I also have the following classes:
Class Helper:
Code java:
public class Helper {
private Super var;
private Class<? extends Super> type;
public void setUp(Class<? extends Super> ty) {
type = ty;
var = type.newInstance();
}
public ???? getSuper() {
return type.cast(var);
}
}
Class SubATest:
Code java:
public class SubATest extends Helper {
public void setUpTest() {
setUp(SubA.class);
}
}
Class SubBTest:
Code java:
public class SubBTest extends Helper {
public void setUpTest() {
setUp(SubB.class);
}
}
Now, Helper is a class that will be used by the various classes which test subclasses of Super. In order to perform various operations, Helper needs access to the subclass variable of Super which is being tested on, so Helper contains a Super object: var, as well as a reference to what subclass var is supposed to be.
I am attempting to create a method which returns var, casted into its intended subclass (getSuper() method), but I am unsure what the return type should be. If I set the return type as a Super object, it will come back uncasted, which defeates the entire purpose of doing this.
My first question is if this is even possible to do. And my second question would be what return type I need to use.
Any help is appreciated.
Re: Creating Method that returns a casted object type
You could think about adding generics to your Helper class. Something like this:
Code java:
class Helper<S extends Super>{
public S getSuper() {
return type.cast(var);
}
}
Re: Creating Method that returns a casted object type
Generics...why didn't I think of that...?
That solves just about every issue. Thanks.