简体   繁体   English

Java泛型-构造函数调用的显式类型参数

[英]Java Generic - Explict type arguments for constructor invocation

I believe I can provide explicit type arguments for the class while invoking constructor with new operator, like this: 我相信我可以在使用新的运算符调用构造函数时为类提供显式类型参数,如下所示:

MyClass<?> obj = new MyClass<Float>("test", 1);

where MyClass is defined like this: MyClass的定义如下:

class MyClass<T>{
    <K, V> MyClass(K k, V v){        
}

I suppose in this case Float is assigned to type parameter T. And for K & V compiler infers the type from actual arguments provided. 我想在这种情况下,将Float分配给类型参数T。对于K&V编译器,它从提供的实际参数中推断出类型。

My doubt is how I can provide explicit type arguments for constructor? 我的疑问是如何为构造函数提供显式类型参数? I know for methods I can do like obj.method<Integer, String>(1, "test"); 我知道对于我可以做的方法,如obj.method<Integer, String>(1, "test");

I wonder is this kind of explicit type arguments(for K&V; not for T) are possible with constructors. 我想知道构造函数是否可以使用这种显式类型参数(对于K&V;不适用于T)。

Hoping somebody can clear this for me. 希望有人可以帮我解决这个问题。 Thanks in advance. 提前致谢。

You give type arguments between new and class name: 您在new和class名称之间输入类型参数:

MyClass<?> obj = new <String, Integer>MyClass<Float>("test", 1);

BTW, for methods you give type argument before method name: 顺便说一句,对于方法,在方法名称之前给类型实参:

obj.<Integer, String>method(1, "test");

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

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