Home » Java » java – How to set a class Name as a method's parameter?-Exceptionshub

java – How to set a class Name as a method's parameter?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment


I would like to send a class name as a parameter of method. I would like to use(execute) it like that.


I have this code

public String getTheMostFrequentType(Class<T> orderClass){
    String tableName = orderClass.getAnnotation(Table.class).name();
    String sqlQuery = "SELECT STATS_MODE(signed_by_id) FROM " + tableName;
    String result = (String)getSessionFactory().getCurrentSession().createSQLQuery(sqlQuery).uniqueResult();
    return result;

But it executing attempts gives me:

getTheMostFrequentType("org.apache.poi.ss.formula.functions.T") method cannot be applied in "java.lang.entities.EmployeeOrder"

May be there is another classes should i import instead of apache.poi. But which one? What i do wrong?

How to&Answers:

If you are using T in a method of class level, you must define it first in class / method definition, unless “T” is unknown.

public class MainClass<T> extends Parent


public <T> String getTheMostFrequentType(Class<T> orderClass)

Another option is not define specific type of T with mark “?”
in your case i think it’s better solution

TIP: Better to not make code complex with generic if it’s not really

like that:

public String getTheMostFrequentType(Class<?> orderClass)


As suggested in the comments, the problem was caused by not declaring a type parameter T but importing an actual type T.

The problem was solved by replacing Class<T> with Class<?>.