gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:04:05 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com