Java generic function: how to return Generic type

后端 未结 6 1943
春和景丽
春和景丽 2020-12-16 15:46

Here\'s a Java generic pattern:

public  T getResultData(Class resultClass, other_args) { 
   ...
   return resultClass.cast(T-thing);
}
         


        
6条回答
  •  一向
    一向 (楼主)
    2020-12-16 16:34

    Yeah I don't think this is possible.

    Imagine this scenario. You have a file with a serialized object that you want to read it. If you make the function generic, you'll be able to use it without a cast. But lets say you have a Map serialized into a file.

    When you deserialize it, there's no way to know what the original generic map type was. As far as java is concerned, it's just a Map

    I ran into this with lists, and it was annoying. But what I actually ended up doing was creating a generic "converting collection" class that takes a collection and a "converter" (which can be an anonymous inner type).

    Then when you iterate through the converting collection, every item gets cast. And that solved the warning problem. It's a lot of work just to get rid of the warning, but I don't think that was the main reason I came up with that framework. You can also do more powerful things like take a collection of filenames, and then write a converter that loads the data in the file, or does a query, or whatever.

提交回复
热议问题