[英]The method insert(String, Class<T>) in the type Data is not applicable for the arguments
I want to have a function that takes in a generic type argument, but I am getting error message for using this.我想要一个接受泛型类型参数的 function,但我收到使用它的错误消息。 How do I use generic the right way in Java?如何在 Java 中正确使用泛型?
Plane plane = new Plane();
Car car = new Car();
data.insert("fast", car);
data.insert("super fast", plane);
...
<T> void insert(String a, Class<T> object) {
System.out.println("Inserting " + object.getName() + a);
}
Your insert function is expecting a Class object like Plane.class
, that's why object.getName()
is known. Your insert function is expecting a Class object like Plane.class
, that's why object.getName()
is known.
I think your intention would be something like:我认为你的意图是这样的:
<T extends HasName> void insert(String a, T object) {
System.out.println("Inserting " + object.getName() + a);
}
where HasName is an interface(could be a super class, too), with method getName
, that is implemented(extended) by Car and Plane.其中 HasName 是一个接口(也可以是一个超级 class),使用方法getName
,由 Car 和 Plane 实现(扩展)。 That's how to ensure that object.getName()
can be called.这就是确保可以调用object.getName()
的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.