Home > Enterprise >  The method insert(String, Class<T>) in the type Data is not applicable for the arguments
The method insert(String, Class<T>) in the type Data is not applicable for the arguments

Time:01-21

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);
}

CodePudding user response:

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.

  •  Tags:  
  • Related