Home  >  Article  >  How to resolve all actual types in java relative to implementation class of generic class or interface?

How to resolve all actual types in java relative to implementation class of generic class or interface?

WBOY
WBOYforward
2024-02-12 18:00:081065browse

Question content

I am trying to resolve all actual types of an implementation class related to a generic class or interface.

I wrote an actualtypeargumentsresolver for this, but it only works if the typename is consistent. I want to ignore typename and get all actual types. How can I achieve this goal?

Any help would be greatly appreciated. Thanks!

@Test
public void testIndirectlyExtendedGenericSuperclassWithDiffTypeName() {

    abstract class AbstractClass3<AAA, BBB, CCC> { }

    abstract class AbstractClass2<AA, BB, CC> extends AbstractClass3<CC, Map, BB> { }

    abstract class AbstractClass1<A, B> extends AbstractClass2<Long, A, Boolean> { }

    class Impl extends AbstractClass1<String, Integer> {}

    Type[] arr = ActualTypeArgumentsResolver.resolve(Impl.class, AbstractClass3.class);

    Assert.assertTrue(arr.length == 3);
    Assert.assertEquals(arr[0], Boolean.class);
    Assert.assertEquals(arr[1], Map.class);
    Assert.assertEquals(arr[2], String.class);
}

Solution

guava's typetoken supports this feature. Use the getsupertype method on the typetoken representing impl to get the parameterized version of abstractclass3 along with all actual type parameters.

65bee58535616

The above is the detailed content of How to resolve all actual types in java relative to implementation class of generic class or interface?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete