我需要检查一个条件,如果它满足,我需要返回一个类,如果它不满足,我需要返回另一个类
private <T> d(String example) {
if(example.startsWith("example1"))
return new example1();
else if((example.startsWith("example2"))
return new example2();
}我不知道怎么退货,你能解释一下吗?
发布于 2012-06-28 13:25:50
private Object getObject(String example) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
if (example.startsWith("example1"))
return Class.forName("example1ClassName").newInstance();
if (example.startsWith("example2")) {
return Class.forName("example2ClassName").newInstance();
}
return null;
}但是正如您注意到的,这个方法抛出了很多异常,所以要小心。您的类可能没有公共默认构造函数或一些类路径问题。它很敏感,需要强制转换操作才能与返回值一起操作。这样做的好处是您可以避免任何继承/超类问题,并且可以使用任何要实例化的类。
https://stackoverflow.com/questions/11238416
复制相似问题