测试对象是否是参数类型的实例 [英] Test if object is instanceof a parameter type

查看:15
本文介绍了测试对象是否是参数类型的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法确定一个对象是否是泛型类型的实例?

Is there a way to determine if an object is an instance of a generic type?

public <T> test(Object obj) {
    if (obj instanceof T) {
        ...
    }
}

这显然行不通.有替代方案吗?就像我想使用 Java 反射来实例化一个类,然后检查以确保它是泛型 T 类型.

That clearly doesn't work. Is there an alternative? Like I want to use Java reflection to instantiate a class and then check to make sure it is of type generic T.

推荐答案

执行此检查的唯一方法是您是否拥有表示类型的 Class 对象:

The only way you can do this check is if you have the Class object representing the type:

Class<T> type; //maybe passed into the method
if ( type.isInstance(obj) ) {
   //...
}

这篇关于测试对象是否是参数类型的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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