简体   繁体   中英

Generic methods in Java

I have more of a .NET background, so I've been having some trouble coming up with a generic method I need in Java. Basically, I have a base class, call it AbstractBase , from which my domain objects inherit from (call them ClassA and ClassB ). I want to write a method that returns a specific type of AbstractBase with a given ID. Here's how I might do it in C#:

public T getById<T>(long id) where T : AbstractBase
{
    if (T is ClassA)
        // find and return object of type ClassA
    else if (T is ClassB)
        // find and return object of type ClassB
    else
        return null;
}

I don't think I have my head fully wrapped around the way Java does generics. Is something like this possible to do with Java? What would be the best approach?

public <T extends AbstractBase> T getById(long id, Class<T> typeKey) {
    if (ClassA.class.isAssignableFrom(typeKey)) {
        // ...
    } else if (ClassB.class.isAssignableFrom(typeKey)) {
        // ...
    } else {
        // ...
    }
}

or if you want exact match on classes (rather than be of a potential subclass type):

public <T extends AbstractBase> T getById(long id, Class<T> typeKey) {
    if (typeKey == ClassA.class) {
        // ...
    } else if (typeKey == ClassB.class) {
        // ...
    } else {
        // ...
    }
}

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