简体   繁体   中英

How to set a class Name as a method's parameter?

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

orderDao.getTheMostFrequentType(EmployeeOrder.class);

I have this code

@Override
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?

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
{...}

or

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 needed.

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<?> .

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