简体   繁体   中英

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. How do I use generic the right way in 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.

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. That's how to ensure that object.getName() can be called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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