简体   繁体   中英

pass a class and returning different class as return object of java generic method

I have a class MyApi with a generic method get() as below.

public class MyApi {

    public <T> T get(Class<T> clazz) {
        // business logic to create and return instance of T
        return null;
    }

}

Which is good so far. But in a few cases, I have to pass a class and will get different class Object in return.

How can I make the same method as generic without introducing a new parameter to same method, for example:

public class MyApi {
    public <T, E> E get(Class<T> clazz1, Class<E> clazz2) {
        // business logic to create and return instance of E
        return null;
    }
}

Eg: To avoid joins on NoSQL I have a Employee class and its materialized view class EmployeeByDepartment . For above api I pass EmployeeByDepartment and expecting Employee object as a response.

If you re-phrase your requirements, you want to return a generic type, but don't care about the parameter type.

This will allow T to be inferred:

public <T> T get(Class<?> clazz) {
    // business logic to create and return instance of T
    return null;
}

Using classes in your example, you could then code:

Employee employee = myApi.get(EmployeeByDepartment.class)

You'll probably need an unchecked cast inside the get() method, but so what.

Your method is trying to do too much, namely, it's trying to resolve the correct class, and then create an object based on that class.

Let's split this up into two methods, one for resolving the correct class, and one for instantiating the object itself.

First, we find the correct class to create:

private Class getCorrectClass(Class<?> clazz) {

    if(clazz.equals(someClass.class)){
        return someOtherClass.class;
    }
    // whatever business logic that
    // will return proper class
    return clazz;
}

Then, we create it:

public <T> T get(Class<?> clazz) {
    Class clazzy = getCorrectClass(clazz);
    // business logic to create and return instance of T
    return (T) clazzy.newInstance(); //or however you decide how to init it
}

Now, whenever you call get, it'll resolve the correct class, then proceed to initialize the proper object.

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