简体   繁体   English

如何定义类型变量以调用Java中的泛型方法

[英]how to define type variable to call generic method in Java

Have a generic method shown below, wants to call the method with a variable which is the matching type. 有一个如下所示的通用方法,想用一个匹配类型的变量来调用该方法。 How to define such variable? 如何定义这样的变量? and how to assign the type to it. 以及如何为其分配类型。

no problem calling it with C1 and C2 用C1和C2调用没问题

t.<C1> getListConfigObjects("foo", String.class);   
t.<C2> getListConfigObjects("foo", String.class);

how to define a variable to call the generics method? 如何定义一个变量来调用泛型方法?

how to do something like this in Java 如何在Java中做这样的事情

Type <? extends JsonXformIntf> theType = C1.getType();
t.<theType> getListConfigObjects("foo", String.class);

theType = C2.getType();
t.<theType> getListConfigObjects("foo", String.class);

Assuming that they both compile, there is absolutely no difference between these two in terms of the compiled bytecode (and thus no possible difference in runtime behavior): 假设它们都可以编译,那么就编译后的字节码而言,这两者之间绝对没有区别(因此,运行时行为也没有可能的区别):

t.<C1>getListConfigObjects("foo", String.class);   
t.<C2>getListConfigObjects("foo", String.class);

Generics is compile-time only. 泛型仅在编译时。 After type erasure, they are both t.getListConfigObjects("foo", String.class); 在类型擦除之后,它们都是t.getListConfigObjects("foo", String.class); . In other words, the type argument you specify is not known to the method at runtime . 换句话说,您指定的类型参数是运行时方法不知道的

The only use of an explicitly-specified type argument is for the compiler's type-checking purposes -- explicitly specifying a right type argument will allow the compiler to compile it (whereas the compiler may otherwise infer it wrong); 显式指定的类型实参的唯一用途是用于编译器的类型检查目的-显式指定正确的类型实参将允许编译器对其进行编译(而编译器可能否则将其推断为错误); conversely, explicitly specifying a wrong type argument will make it not compile. 相反,显式指定错误的类型参数将使其无法编译。 However, if they both compile, then there is no difference. 但是,如果它们都编译,则没有区别。

Therefore, it wouldn't make sense to specify a type argument that is not known at compile-time, because compile-time is the only time when such a type argument is used at all. 因此,指定在编译时不知道的类型参数是没有意义的,因为只有在完全使用这种类型参数的情况下,编译时才是。 Simply pick any type argument that allows it to compile. 只需选择任何允许其编译的类型参数即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM