假设我有一个基类:
abstract class TheBase {}
class Foo extends TheBase {}
class Bar extends TheBase {}
我想将基础对象“转换”为这种类型:
TheBase obj = getFromSomewhere();
Foo foo = obj.asA(Foo.class);
Bar bar = obj.asA(Bar.class);
asA
将抛出一个我定义的异常:CustomCannotCastException()
这可能吗?
最佳答案
你需要这样的东西吗?
public class TheBase {
public <T> T asA(Class<T> claxx) {
if (claxx.isInstance(this)) {
return claxx.cast(this);
} else {
throw new CustomCannotCastException();
}
}
}
关于java - 使用 Java 转换基本类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13508202/