只有在运行时才知道类型的Java泛型的用法 [英] Usage of Java generics when the type is known only at runtime

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

问题描述

请考虑以下代码:

  public class Generics {
C c; //在运行时初始化

public void testGenericsCall(Object o){
c.myMethod(o);
}
}

class C< E> {
public void myMethod(E input){
}
}



<这是工作,但我得到警告,因为参数化的类C与原始类型一起使用。我不能使用像

这样的声明。

  C< String> C; 

因为只有在运行时才知道C的类型。我也无法向类泛型添加类型参数,因为在知道类型C之前我需要创建此类的对象。声明

  C<?> C; 

  C< ;?扩展对象> C; 

对于编译器是可以的,但是testGenericsCall方法不会编译(actual参数java.lang.Object不能被转换为通过方法调用转换捕获#1)

处理一个情况的最好方法是什么像这样?



编辑:注意,当我实际上(在运行时)创建一个C的实例时,我知道它的类型参数,的代码是类型安全的并且运行良好。在真正的代码中,我没有一个C类,而是一系列相关的类,而且泛型是绝对有用的(即使在这个简化的例子中这并不明显 - 所以请不要仅仅告诉我不使用泛型:)。我已经有编译时类型安全性,但不在这里,但在C和其他类之间(这里没有显示)。



我看到在这种情况下,我不能在编译时检查类型参数,这就是为什么我试图声明 C<> ç。这里我只是寻找最好的方法来在没有编译器警告的情况下桥接泛型代码和非泛型代码。

解决方案

由于键入删除,因此无法在运行时使用泛型。你必须以编程方式处理你的数据类型,通过检查类型或任何东西(反射可能)。


Consider the following code:

public class Generics {
    C c; // initialized at runtime

    public void testGenericsCall(Object o) {
        c.myMethod(o);
    }
}

class C<E> {
    public void myMethod(E input) {
    }
}

This is working, but I get warnings because the parametrized class C is used with a raw type. I cannot use a declaration like

C<String> c;

because the type of C is known only at runtime. I also cannot add a type parameter to the class Generics because I need to create objects of this class before knowing the type of C. The declaration

C<?> c;

or

C<? extends Object> c;

would be OK for the compiler, but then the method testGenericsCall does not compile ("actual argument java.lang.Object cannot be converted to capture#1 of ? by method invocation conversion")

What is the best way to deal with a situation like this?

EDIT: Note that when I actually (at runtime) create an instance of C, I know its type parameter, this part of the code is type-safe and working well. In the real code, I don't have a single "C" class, but a series of interrelated classes, and there the generics are definitely useful (even if in this simplified example this is not obvious - so please don't just tell me not to use generics :). I already have the compile-time type-safety, but not here, but between C and other classes (not shown here).

I see how in this case I cannot check the type parameter at compile time, that's why I tried to declare it C<?> c. Here I am just looking for the best way to bridge the generic and not-generic code without compiler warnings.

解决方案

Because of type erasure, there's no way to use generics at runtime. You'll have to deal with your data type programmatically, by checking type or anything (reflection maybe).

这篇关于只有在运行时才知道类型的Java泛型的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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