[英]Different return type for the same method
i need to implement the newInstance method in order to make this code to work: 我需要实现newInstance方法,以使此代码工作:
protected IDatabase createDatabase() throws Exception{
return newInstance(CLASS_NAME_DATABASE);
}
protected IDataLoader createDataLoader() throws Exception{
return newInstance(CLASS_NAME_DATA_LOADER);
}
I'm not allowed to touch this code, but when i try to implement the newInstance as Object it means i need to cast the newInstance in the code above you. 我不允许触摸此代码,但是当我尝试将newInstance实现为Object时,这意味着我需要在您上面的代码中强制转换newInstance。 Is there a way for me to implement newInstance without changing the code? 有没有办法在不更改代码的情况下实现newInstance?
Thanks! 谢谢!
If the parameter to newInstance
were a Class
object, or something else with a generic type parameter, you could do the following, which would avoid needing to cast the return value, and be type-safe: 如果newInstance
的参数是Class
对象,或带有泛型类型参数的其他参数,则可以执行以下操作,这将避免需要强制转换返回值,并且是类型安全的:
protected <T> T newInstance(Class<T> klass) throws Exception {
return klass.newInstance();
}
(Note: klass.newInstance()
is the reflection API method, not the same as the method being defined, despite the same name.) (注意: klass.newInstance()
是反射API方法,与定义的方法不同,尽管名称相同。)
However, you can use generics no matter what sort of parameters newInstance
takes: 但是,无论newInstance
采用什么类型的参数,您都可以使用泛型:
@SuppressWarnings("unchecked")
protected <T> T newInstance(String className) throws Exception {
return (T)Class.forName(className).newInstance();
}
This is a bit dirty, because it completely eliminates compile-time error checking on the type of the return value. 这有点脏,因为它完全消除了返回值类型的编译时错误检查。 The compiler will allow IDataLoader x = newInstance(CLASS_NAME_DATA_LOADER);
编译器将允许IDataLoader x = newInstance(CLASS_NAME_DATA_LOADER);
but will just as happily allow int x = newInstance(CLASS_NAME_DATA_LOADER);
但同样乐意允许int x = newInstance(CLASS_NAME_DATA_LOADER);
(which actually casts it to an Integer
then unboxes it). (实际上将它转换为Integer
然后将其取消装箱)。
However, manually casting an Object
return value would also not be checked at compile time, so using generics here is probably still an improvement since it reduces the number of times you have to write each type. 但是,在编译时也不会检查手动转换Object
返回值,因此在此处使用泛型可能仍然是一种改进,因为它减少了您必须编写每种类型的次数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.