[英]Avoiding warnings on unchecked cast exceptions for classes?
Code first: ) 代码优先:)
/**
*
* @param arrayList the ArrayList
* @return a random object from the ArrayList
*/
public static Object randomArrayListObject(ArrayList<?> arrayList) {
Random random = new Random();
int i = random.nextInt(arrayList.size());
assert i >= 0;
assert i < arrayList.size();
return arrayList.get(i);
}
public static Class<? extends Juice> randomArrayListJuiceClass(
ArrayList<Class<? extends Juice>> arrayList) {
final Object o = randomArrayListObject(arrayList);
assert Juice.class.isAssignableFrom((Class) o);
if (Juice.class.isAssignableFrom((Class) o)) {
@SuppressWarnings("unchecked")
Class c = (Class<? extends Juice>) o;
return c;
} else throw new RuntimeException("wtf? not a Juice Class??");
}
I'm getting this warning: 我收到此警告:
Unchecked assignment: 'java.lang.Class' to 'java.lang.Class<?
未检查的赋值:“ java.lang.Class”到“ java.lang.Class <? extends drinks.Juice>'
扩展饮料。果汁>
I put all that monster code in randomArrayListJuiceClass()
to try to avoid such warnings but still I can't figure it out. 我将所有这些
randomArrayListJuiceClass()
代码都放在randomArrayListJuiceClass()
以尝试避免此类警告,但是我仍然无法弄清楚。 What can I do? 我能做什么?
My goal is just to return the (some kind of) Juice
Class without warnings... I know I'm only feeding randomArrayListJuiceClass()
some Juice
, I just have it throwing an Exception
just in case I was sloppy and fed it something else. 我的目标只是在没有警告的情况下返回(某种)
Juice
类...我知道我只是在给Juice
喂randomArrayListJuiceClass()
,我只是抛出了一个Exception
,以防万一我马虎并喂了别的东西。
What should I do? 我该怎么办?
Your method for getting a random element should be generic and bind its return type to the type of the input ArrayList
您获取随机元素的方法应该是通用的,并将其返回类型绑定到输入
ArrayList
的类型
public static <T> T randomArrayListObject(ArrayList<T> arrayList) {
Your other code then becomes 您的其他代码将变为
final Class<? extends Juice> o = randomArrayListObject(arrayList);
assert Juice.class.isAssignableFrom(o); // even this is kind of useless
return o;
Assuming your assertions are on, you won't need another exception thrown. 假设您的断言存在,您将不需要抛出另一个异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.