Cannot resolve generic parameter TypeToken from Guava

后端 未结 1 1430
天涯浪人
天涯浪人 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条回答
  •  -上瘾入骨i
    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
    

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

    MenuOptionBuilder builder = 
        new MenuOptionBuilder(new MenuOptionBean()) {};
    

    then you will get Link.

    In this case

    MenuOptionBuilder builder = 
        new MenuOptionBuilder(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>?

    0 讨论(0)
提交回复
热议问题