检查字段类型是否与java中的泛型类型相同 [英] Check if field type is same as generic type in java

查看:417
本文介绍了检查字段类型是否与java中的泛型类型相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



例如

pre> Foo扩展Bar< Foo>

Foo x;

如何判断字段x是否为 Bar<的子类型; Foo>

解决方案>

 键入genericSuperclass = x。 。的getClass()getGenericSuperclass(); $(b)(b)如果(genericSuperclass instanceof ParameterizedType){
Type [] types =
((ParameterizedType)genericSuperclass).getActualTypeArguments();
}

然后您可以使用 Class.isAssignableFrom ,如果类型instanceof Class ,以验证它是否是 Foo 或不是。





  if(types [0] instanceof Class){
if(x.getClass()。isAssignebleFrom(( Class)类型[0]))){
//做某事
}
}


I want to determine if a field is typed as the subclass of a generic type.

For e.g

Foo extends Bar<Foo>

Foo x;

How do I tell if the field x is typed as a subtype of Bar<Foo>?

解决方案

Type genericSuperclass = x.getClass().getGenericSuperclass();
if (genericSuperclass instanceof ParameterizedType) {
    Type[] types = 
       ((ParameterizedType) genericSuperclass).getActualTypeArguments();
}

Then you can use Class.isAssignableFrom, if type instanceof Class, to verify whether it is Foo or not.

i.e.

if (types[0] instanceof Class) {
    if (x.getClass().isAssignebleFrom(((Class) type[0]))){
        // do something
    }
}

这篇关于检查字段类型是否与java中的泛型类型相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆