在运行时确定通用方法参数的类型 [英] Determining the Type for a generic method parameter at runtime

查看:89
本文介绍了在运行时确定通用方法参数的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个具有以下结构的类。我试图确定泛型方法的调用者分配的参数T的类型。

  public class MyClass {

public< T>布尔IsSupportable(){

Class typeOfT; //需要确定泛型参数的类T

//商业逻辑去这里

return true;




$ b在C#中,我会使用default(T)或typeof(T),但我试图在Java中做到这一点。有谁知道如何/如果我可以做到这一点?我真的不需要一个实例,我只需要类定义。

解决方案

你不能这样做。你可以做的是使方法签名像这样:

pre $ $ $ $ c $ public boolean isSupportable(Class<> type)

然后您可以使用给定的类来检查类型。


Given the a class with the following structure. I am trying to determine the type of the parameter T assigned by the caller of the generic method.

public class MyClass{

    public <T> Boolean IsSupportable() {

        Class typeOfT; // Need to determine Class for generic parameter T

        // Business Logic goes here 

        return true; 
    }
}

In C# I would use "default(T)" or "typeof(T)" but I am trying to do this in Java. Does anyone know how/if I can do this? I don't really need an instance, I just need the Class definition.

解决方案

You can't do that. What you could do is make the method signature like this:

public boolean isSupportable(Class<?> type)

Then you can use the given class to check the type.

这篇关于在运行时确定通用方法参数的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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