简体   繁体   English

传递一个类并返回不同的类作为java泛型方法的返回对象

[英]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. 我有一个具有通用方法get()的类MyApi ,如下所示。

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. 但是在某些情况下,我必须传递一个类,并将获得不同的类Object作为回报。

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 . 例如:为避免在NoSQL上进行联接,我有一个Employee类及其物化视图类EmployeeByDepartment For above api I pass EmployeeByDepartment and expecting Employee object as a response. 对于上述api,我传递EmployeeByDepartment并期望Employee对象作为响应。

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: 这将可以推断出T

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. 您可能需要在get()方法中进行未经检查的强制转换,但那又如何。

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. 现在,无论何时调用get,它将解析正确的类,然后继续初始化适当的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM