简体   繁体   中英

Generic method without type argument

I was wondering if there's a way to, in Java, use a generic type within a generic method without requiring an argument specifying the class type. Here's the normal way of doing it:

public <T> T doSomethingGeneric(Class<T> type, int a) {
    return (T) doSomethingElse(type, a);
}

I would like this as an alternative:

public <T> T doSomethingGeneric(int a) {
    return (T) doSomethingElse(/* some magic with T here */, a);
}

Background: I'm writing utility methods with Hibernate. Here's an example of what I'm actually trying to do, and you can infer how it applies to this problem.

public static <M extends Model> M get(Class<M> type, Serializable id) {
    Session session = newSession();
    Transaction t = session.beginTransaction();
    Object model = null;
    try {
        model = session.get(type, id);
        t.commit();
    } catch (HibernateException ex) {
        t.rollback();
        throw ex;
    }
    return (M) model;
}

Is this possible? If so, how is it done? Thanks!

You want to get a Class<T> at runtime to pass to doSomethingElse() ? No, that is not possible.

If you describe why doSomethingElse needs a Class<T> , perhaps we could suggest a workaround.

This isn't possible: the code of doSomethingGeneric is only compiled once, unlike the instantiation of a template in C++. The type T is erased to Object in the process.

Notice also that (T) will be flagged as an unchecked downcast.

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