简体   繁体   中英

Implement generic return type for methods in Java

Hello I have few model return types and a rest call that can have any one of those return type. I want to implement generics or something like that which enables to return the expected type model. For example:

Conside I have 2 models ItemDetails.java and ItemDetailsWithTimestamp.java In one case i need to return the first model and in another case i want the second one: I tried something like:

Test.java

@Test
public void getitemTest() {
    ItemApi itemApi = new ItemApi();
    ItemDetails result = itemApi.getitem(ItemDetails.class);
} 
    
public void getitemWithTimestampTest() {
    ItemApi itemApi = new ItemApi();
    ItemDetailsWithTimestamp result = itemApi.getitem(ItemDetailsWithTimestamp.class);
} 

And in the ItemApi class the method getitem :

public static <T> ResponseEntity<T> getitem(Class<T> type) {
    #somecode for implementing rest calls
    return (ResponseEntity<T>) response;
}

Note: This is not the full code as seen but the extract which is perhaps enough to explain the problem. The above code returns an error on running the test:

java.lang.ClassCastException: class java.util.LinkedHashMap cannot be cast to class myproject.model.ItemDetails (java.util.LinkedHashMap is in module java.base of loader 'bootstrap'; myproject.model.ItemDetails is in unnamed module of loader 'app')

What could be the issues, is it not possible to accommodate different types using this approach or do i miss something. Thanks in advance,

One way to deal with this:

interface ItemDetails{}

class ItemDetailDtoWithTimeStamp implements ItemDetails{}

class ItemDetailsWithSomething implements ItemDetails{}

While returning, your return type should be ItemDetails (interface) and ResponseEntity<ItemDetails>

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