具有通用返回类型的Java方法 [英] Java method with generic return Type
问题描述
Java中是否有一种方法可以通过一个方法的声明返回不同的类型?
Is there a way in Java to return different types with one declaration of a method?
public Object loadSerialized(String path) {
Object tmpObject;
try {
FileInputStream fis = new FileInputStream(path);
ObjectInputStream ois = new ObjectInputStream(fis);
tmpObject = (Object) ois.readObject();
ois.close();
fis.close();
return tmpObject;
} catch (FileNotFoundException e) {
return null;
} catch (Exception e) {
}
}
我希望此方法返回一个Object,然后在函数调用中将其云转换为正确的类型。那是我的想法,但这种方式无法正常工作。我需要某种通用的返回类型来做到这一点吗?
解决此问题的最佳方法是什么?
I want this method to return an Object and I cloud cast it to the right type at the function call. That was what i thought but it doesn't work like this. Do I need some kind of generic return Type to do this? What would be the best way to solve this problem?
推荐答案
要安全地执行此操作,您需要传递所需的类型作为Class对象:
To do this safely, you need to pass in the desired type as a Class object:
public <T> T loadSerialized(String path, Class<T> targetType) {
try (ObjectInputStream ois = new ObjectInputStream(
new BufferedInputStream(
new FileInputStream(path)))) {
Object tmpObject = (Object) ois.readObject();
return targetType.cast(tmpObject);
} catch (FileNotFoundException e) {
return null;
} catch (IOException | ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
可以写 return(T)tmpObject;
,将生成编译器警告,因为它不安全:因为编译器只知道T可能是Object(或Object本身)的后代),编译器会生成(Object)
,这与不执行任何操作相同。该代码盲目地假定返回的对象是T类型,但是如果不是,则当程序尝试调用T中定义的方法时,您将得到一个意外的异常。最好在对对象进行反序列化后立即知道它是否为预期的类型。
While you could write return (T) tmpObject;
, that will generate a compiler warning, because it is not safe: since the compiler only knows that T might be some descendant of Object (or Object itself), the compiler generates (Object)
, which is the same as doing nothing at all. The code blindly assumes the returned object is of type T, but if it isn’t, when the program tries to call a method defined in T, you’ll get a surprise exception. It’s better to know as soon as you have deserialized the object whether it was the type you expected.
如果对a执行不安全的转换,也会发生类似的情况列表:
A similar thing happens if you do an unsafe cast on, say, a List:
List<Integer> numbers = Arrays.asList(1, 2, 3);
List<?> list = numbers;
List<String> names = (List<String>) list; // Unsafe!
String name = names.get(0); // ClassCastException - not really a String!
这篇关于具有通用返回类型的Java方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!