Cannot resolve generic parameter TypeToken from Guava

后端 未结 1 1428
天涯浪人
天涯浪人 2021-01-27 19:23

I am developing a framework for building generified menus for a Selenium testing framework, and I\'ve been using Guava TypeToken to resolve the types of generic parameters, but

相关标签:
1条回答
  • 2021-01-27 19:37

    That's how the TypeToken "hack" works. It uses Class#getGenericSuperclass() (or getGenericSuperInterface). Its javadoc states

    If the superclass is a parameterized type, the Type object returned must accurately reflect the actual type parameters used in the source code.

    In this case, that is O, here

    public abstract class AbstractMenuOptionBuilder<O extends IClickable>
    

    You get what is hard coded in the source code. If you hard code Link as the type argument, as you do here

    MenuOptionBuilder<Link> builder = 
        new MenuOptionBuilder<Link>(new MenuOptionBean()) {};
    

    then you will get Link.

    In this case

    MenuOptionBuilder<O> builder = 
        new MenuOptionBuilder<O>(new MenuOptionBean()){};
    

    you've hard coded O, so that's what you will get.

    Here are some more things I've written on the subject of type tokens:

    • Gson TypeToken with dynamic ArrayList item type
    • is it possible to use Gson.fromJson() to get ArrayList<ArrayList<String>>?
    0 讨论(0)
提交回复
热议问题