I have read other related posts, but am still not quite sure how, or if it is possible to Dynamically cast (Interface to Implementation) in Java. I am under the impression that I must use Reflection to do so.
The particular project I am working on requires a usage of many instanceof
checks, and it is, in my opinion getting a bit out of hand, so would appreciate any ideas/solutions.
Below is a mini example I wrote up just to clarify exactly what I'm wanting to do . Let me know if you need more information:
Interface:
public interface IRobot {
String getName();
}
Implementations:
public class RoboCop implements IRobot {
String name = this.getClass()+this.getClass().getName();
public RoboCop() {}
public String getName() { return name; }
}
public class T1000 implements IRobot {
String name = this.getClass()+this.getClass().getName();
public T1000() {}
public String getName() { return name; }
}
The Class that handles the implementations:
import java.util.LinkedList;
import java.util.List;
public class RobotFactory {
public static void main(String[] args) {
new RobotFactory();
}
public RobotFactory() {
List<IRobot> robots = new LinkedList<IRobot>();
robots.add( new RoboCop() );
robots.add( new T1000() );
System.out.println("Test 1 - Do not cast, and call deploy(robot)");
for(IRobot robot : robots) {
deploy(robot); // deploy(Object robot) will be called for each..
}
System.out.println("Test 2 - use instanceof");
for(IRobot robot : robots) { // use instanceof, works but can get messy
if(robot instanceof RoboCop) {
deploy((RoboCop)robot);
}
if(robot instanceof T1000) {
deploy((T1000)robot);
}
}
System.out.println("Test 3 - dynamically cast using reflection?");
for(IRobot robot : robots) {
//deploy((<Dynamic cast based on robot's type>)robot); // <-- How to do this?
}
}
public void deploy(RoboCop robot) {
System.out.println("A RoboCop has been received... preparing for deployment.");
// preparing for deployment
}
public void deploy(T1000 robot) {
System.out.println("A T1000 has been received... preparing for deployment.");
// preparing for deployment
}
public void deploy(Object robot) {
System.out.println("An unknown robot has been received... Deactivating Robot");
// deactivate
}
}
Output:
[RoboCop@42e816, T1000@9304b1]
Test 1 - Do not cast, and call deploy(robot)
An unknown robot has been received... Deactivating Robot
An unknown robot has been received... Deactivating Robot
Test 2 - use instanceof
A RoboCop has been received... preparing for deployment.
A T1000 has been received... preparing for deployment.
Test 3 - dynamically cast using reflection?
So, to sum up my question, how can I completely avoid having to use instanceof
in this case. Thanks.