java - 如何将 "dynamically"对象类型的实例转换为其特定数据类型?

标签 java reflection types casting dynamic

public Object foo(int opt){
  if (opt == 0) return new String();
  else if (opt == 1) return new Integer(1);
  else if (opt == 2) return new Double(1);
  else if ...
  .. and many more
}

public void doSomething(String s){..}
public void doSomething(Integer i){..}
public void doSomething(Double d){..}
... and many more doSomething method

public static void main(String[] args){
  ...
  Object o = foo(x); //x is a value obtained during runtime, e.g. from user input

  //now I want to call doSomething method
  // (1)
  if (o instanceof String) doSomething((String) o);
  else if (o instanceof Integer) doSomething((Integer) o);
  else if (o instanceof Double) doSomething((Double) o);
  ...
  // (2)
}

有没有更好的方法来简化 (1) ... (2) 所包含的语句?
Java 反射有帮助吗?

最佳答案

高效、干净地处理此问题的最佳方法是让 foo 返回对象的持有者类。

abstract class Holder<T> {
    private final T object;

    protected Holder(T object) { this.object = object; }
    public T get() { return object; }
    public abstract void doSomething();
}

public Holder foo(int opt) {
    if (opt == 0) return new Holder<String>("") {
        public void doSomething() { }
    };
    else if (opt == 1) return new Holder<Integer>(1) {
        public void doSomething() { }
    };
    else if (opt == 2) return new Holder<Double>(1.0) {
        public void doSomething() { }
    };
    // many more
}

public static void main(String... args) throws IOException {
    Holder h  = foo(x); //x is a value obtained during runtime, e.g. from user input

    //now I want to call doSomething method
    h.doSomething();
}

关于java - 如何将 "dynamically"对象类型的实例转换为其特定数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5617039/

相关文章:

c# - 从结构的常量属性中获取值的集合

java - 是否可以调用模拟对象的方法?

java - 在 log4j JDBCAppender 中保存额外的值

java - 从 Spring Boot 1.5-2、Spring Security 4-5 升级后,Spring security 不再重定向到登录页面

java - 使用与 xml 适配器一起使用的自定义类型编码空值

types - Julia 是动态类型的吗?

python - type(4) == type(int) 在 Python 中是 False 吗?

java - 如何使用 Grails oauth 插件获取访问 token ?

c# - 来自静态反射的动态场?

asynchronous - 异步方法中的类型不匹配