Java – 从接口到实现的动态类转换

前端之家收集整理的这篇文章主要介绍了Java – 从接口到实现的动态类转换前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经阅读了其他相关的帖子,但仍然不太清楚如何,或者是否可以在 Java中动态地(实现的接口).我的印象是我必须用反思去做.

我正在开展的具体项目需要使用许多支票实例,而且在我看来,这是一个不合时宜的事情,所以不妨感谢任何想法/解决方案.

下面是一个迷你的例子,我写的只是为了澄清我想要做什么.如果您需要更多信息,请告诉我们

接口:

public interface IRobot {
    String getName();
}

实现:

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; }
}

处理实现的类:

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
    }
}

输出

[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?

所以,总结一下我的问题,在这种情况下我怎么能完全避免使用instanceof.谢谢.

解决方法

您可以部署IRobot的方法,或使用 visitor pattern.

不,反思不会让事情变得更容易.

原文链接:https://www.f2er.com/java/123713.html

猜你在找的Java相关文章