[英]Type-safe way to cast object to Class
I want to remove the suppression of the unchecked conversion warning. 我想删除对未选中的转换警告的抑制。 How can I cast
o
to T
with complete surety? 我怎样才能完全保证将
o
投给T
?
Of note: the ResultSet in this snippet is a proprietary wrapper that is source-agnostic. 注意:此代码段中的ResultSet是与源无关的专有包装器。 It's very similar to java.sql.ResultSet, but it is not the same.
它与java.sql.ResultSet非常相似,但是并不相同。 Also, using Eclipse Mars.1 with Java 8 u45, and both the IDE and javac issue the warning.
另外,将Eclipse Mars.1与Java 8 u45一起使用,IDE和Javac均会发出警告。 I realize that since it's wrapped in that
if
statement, that it's technically not an issue, but I absolutely hate to suppress warnings. 我意识到,由于它包含在
if
语句中,因此从技术上讲这不是问题,但是我绝对不喜欢抑制警告。 And I feel like there's gotta be a completely type-safe way to perform that conversion. 而且我觉得必须有一种完全类型安全的方法来执行该转换。
public class ResultSetQuery {
public static <T> List<T> collectValues(ResultSet rs, String keyName, Class<T> tclass) {
List<T> result = new LinkedList<>();
while(rs.next()) {
Object o = rs.getData(keyName);
if (tclass.isAssignableFrom(o.getClass())) {
@SuppressWarnings("unchecked")
T v = (T)o;
result.add(v);
} else {
result.add(null);
}
}
return result;
}
}
Your intention to not blindly silence compiler warnings is honorable but your code example is a good example for a justified use of @SupressWarnings
. 您打算不盲目地使编译器警告
@SupressWarnings
是可以接受的,但是您的代码示例是@SupressWarnings
合理使用的一个很好的示例。 Your code cannot fail, and still the compiler complains, therefore @SupressWarnings
is the way to go. 您的代码不会失败,并且编译器仍会抱怨,因此
@SupressWarnings
是解决之道。
Take a look at java.lang.Class#cast
which has the same pattern as your example. 看一下与您的示例具有相同模式的
java.lang.Class#cast
。 It also suppresses the warning: 它还抑制了警告:
@SuppressWarnings("unchecked")
public T cast(Object obj) {
if (obj != null && !isInstance(obj))
throw new ClassCastException(cannotCastMsg(obj));
return (T) obj;
}
You can write: 你可以写:
if (tclass.isAssignableFrom(o.getClass())) {
result.add(tclass.cast(o));
}
(See https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#cast(java.lang.Object) .) (请参阅https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#cast(java.lang.Object) 。)
Edited to add: Incidentally, as erickson points out in a comment, you should probably be writing tclass.isInstance(o)
instead of tclass.isAssignableFrom(o.getClass())
: it's simpler and clearer, and it avoids a NullPointerException when o
is null. 编辑添加:顺便提一句,正如erickson在评论中指出的那样,您可能应该编写
tclass.isInstance(o)
而不是tclass.isAssignableFrom(o.getClass())
:它更简单tclass.isAssignableFrom(o.getClass())
,并且当o
时避免了NullPointerException一片空白。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.