本文介绍了泛型和Class.asSubclass的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直认为以下几点应该有效。我得到一个我知道的对象是一个类< X> 其中 X 扩展了一些类 XYZ 。为了使其类型安全,我想使用Class.asSubclass,如以下方法:

  private Class<?扩展Xyz> castToXyzClass(Object o){
final Class<?> resultClass =(Class<?>)o;
final Class<?扩展Xyz> result = Xyz.class.asSubclass(resultClass);
返回结果;
}

然而,在Eclipse中它不起作用,唯一的解决方案是未经检查的演员。我敢打赌上面的代码必须工作,我已经使用了这样的东西...不知道这里有什么问题。

解决方案

p> asSubclass()对所调用的对象进行操作,而不是在其参数上操作,而不是使用它,但读取的相当好。你只需要这样做:

  final Class<?扩展Xyz> result = resultClass.asSubclass(Xyz.class); 


I've always thought the following should work. I get an object which I know is a Class<X> where X extends some class Xyz. In order to make it type-safe I wanted to use Class.asSubclass like in the following method:

private Class<? extends Xyz> castToXyzClass(Object o) {
    final Class<?> resultClass = (Class<?>) o;
    final Class<? extends Xyz> result = Xyz.class.asSubclass(resultClass);
    return result;
}

However, in Eclipse it doesn't work, the only solution I see is an unchecked cast. I'd bet the above code must work, I've used something like this already... no idea what's wrong here.

解决方案

asSubclass() operates on the object it's called on, not on its parameter - not what one is used to, but it reads quite well. You just have to do this:

final Class<? extends Xyz> result = resultClass.asSubclass(Xyz.class);

这篇关于泛型和Class.asSubclass的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 10:52