简体   繁体   中英

In which case `ParameterizedType#getActualTypeArguments` return an array which has more than one elements

I tried to get the classtype in the generic,and code below works:

@Test
public void test3() throws NoSuchFieldException {
    Class<?> clazz = (Class<?>) ((ParameterizedType)Role.class.getDeclaredField("users")
            .getGenericType()).getActualTypeArguments()[0];
    assert clazz.equals(User.class) : "error!";
}

static class Role {
    public List<User> users;
}
static class User {

}

So, I learned something about ParameterizedType .

And I want to know in which case ParameterizedType#getActualTypeArguments return an array which has more than one elements.I tried a lot of cases, but all the results are an array of size 1.

Any ideas?

It return an array of more than one element if you have several generic parameters like in Map.

Example:

@Test
public void exampleTest() {
    Map<Integer, String> myMap = new HashMap<>();
    ParameterizedType type = (ParameterizedType) myMap.getClass().getGenericSuperclass();
    System.out.println("Array of actual types : " + Arrays.toString(type.getActualTypeArguments()));
}

And the output is:

Array of actual types: [K, V]

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