I need to instantiate an object of one of two different types, depending on a conditional. Both types take the same arguments to their constructors, and both are subclasses of a master type. Can I define a reference to the correct type inside the conditional and then instantiate the object using that reference? Quick example:
if (v == "bob") {
Object myType = bobType;
} else {
Object myType = otherType;
}
SuperType instance = new myType(arg1, arg2);
This doesn't work; is there a correct syntax for this in java? This is as a shortcut to doing this:
if (v == "bob") {
SuperType instance = new bobType(arg1, arg2);
} else {
SuperType instance = new otherType(arg1, arg2);
}
I'm actually making several instances, all of the same type, that all take a long list of arguments, and I wanted to avoid exactly repeating myself except for the type. everyone's answers are amazing; i wish i could accept more than one. i'm going to accept jacobm's because he explains the correct way to do something like this (although, yeah, it's a little verbose).
以上就是Java: Reference to a type?的详细内容,更多请关注web前端其它相关文章!