使用者接口中的Java泛型类型参数
在下面类的main方法中使用了下面的方法:input 但是,这将导致编译错误,如下所示,包装在使用者中的字段数量是对象的实例,而不是可以模制为int的泛型类型 因此,为了解决编译错误,我们需要将(int)转换为amount,然后使用ok((int)amount)使用者接口中的Java泛型类型参数,java,syntax,compiler-errors,generic-programming,Java,Syntax,Compiler Errors,Generic Programming,在下面类的main方法中使用了下面的方法:input 但是,这将导致编译错误,如下所示,包装在使用者中的字段数量是对象的实例,而不是可以模制为int的泛型类型 因此,为了解决编译错误,我们需要将(int)转换为amount,然后使用ok((int)amount) 公共类构造函数{ 公共静态void main(字符串…参数){ 输入(“原因”,(金额)->{ int-amount2=amount;//也有错误,因为amount是对象而不是int ok(amount);//错误,因为amount是O
公共类构造函数{
公共静态void main(字符串…参数){
输入(“原因”,(金额)->{
int-amount2=amount;//也有错误,因为amount是对象而不是int
ok(amount);//错误,因为amount是Object而不是int
});
}
公共静态void ok(int i){//参数i必须是整数
}
公共静态无效输入(字符串原因、使用者答案){
}
}
我希望能够将消费者中的金额值作为int/string/list自由使用
以下是我想如何免费使用金额字段的示例:
usage:
ok(attribute("key"); //this will work and is freely moldable into int/string/whatever
code:
public <T> T attribute(String key){ //This will return whatever you want it to, and is how I want the amount field to do inside the consumer
return aHashMap.get(key);
}
用法:
ok(attribute(“key”);//这将起作用,并且可以自由地转换为int/string/whatever
代码:
public T attribute(String key){//这将返回您想要的任何内容,这就是我希望amount字段在使用者中执行的操作
返回aHashMap.get(键);
}
这里最接近的问题是Java编译器没有根据来推断方法input()
的类型参数T
。您可以通过使用几种显式表示方法中的任何一种来解决这个问题。例如
<Integer>input("reason", (amount) -> {
int amount2 = amount; //also error as amount is Object and not int
ok(amount); //error as amount is Object and not int
});
,但这本身并不能帮助Java推断调用该方法的使用者的类型参数
我希望能够将消费者中的金额值作为int/string/list自由使用
如前所述,这没有任何意义。消费者
实现中存在局部变量金额
,这是该实现的一个细节。因此,以任何方式使用参数的实现(不是所有对象
通用的)仅限于与类型子集一起使用。因为字符串
、List
和Integer
没有比Object
更具体的公共超类,没有这样的使用者可以处理这三种类型。对于这些类型中的每一种,您可以有不同的使用者
实现,但是对于这些使用者所共有的数量没有意义。Java是一种静态类型的语言,每个变量只有一种类型。不能像“int/string/list”那样随意使用同一个变量。此外,类型推断机制是有限的-它不会看到您稍后使用参数调用带有int
参数的方法;这对它推断的类型没有影响。如果泛型类型在您使用它的位置没有限制,编译器将推断对象
,并使用它完成。考虑到op中的第二个代码块表明泛型类型可以在一些更动态、更少静态的编写中使用,java是否无法将amount识别为一个泛型类型,它可以是int而不仅仅是一个对象?@kay第二个代码块没有编译,是吗?@Sweeper it doesFirst,您缺少了一个结束语)
在第一行。其次,无论HashMap
aHashMap
是什么类型,它都可能不是HashMap
,因为T
可以随着对属性的每个方法调用而改变。你可能需要一个未经检查的演员阵容。
<Integer>input("reason", (amount) -> {
int amount2 = amount; //also error as amount is Object and not int
ok(amount); //error as amount is Object and not int
});
Consumer<Integer> intConsumer = (amount) -> {
int amount2 = amount; //also error as amount is Object and not int
ok(amount); //error as amount is Object and not int
};
input("reason", intConsumer);
public static void input(String reason, Consumer<Integer> answer){
// ...
}
public static void input(String reason, Consumer<?> answer){
// ...
}