Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9224831
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T04:25:28+00:00 2026-06-18T04:25:28+00:00

I have a specific target type (decided at runtime), and an iterable class that

  • 0

I have a specific target type (decided at runtime), and an iterable class that I’m comparing to it. I’m trying to write a method that checks the generic parameters of the class, to see if it’s an iterable of something that subclasses my target type. Examples:

Class<?> X = SomeObject.class;

matches(X, new ArrayList<SomeObject>()) -> true
matches(X, new ArrayList<SubclassOfSomeObject>()) -> true
matches(X, new ArrayList<SomeOtherObject>()) -> false
matches(X, new ArrayList()) -> true (I think?)
matches(X, new Iterable<SomeObject>() { ... }) -> true
matches(X, new ListOfSomeObjects()) -> true 
                       (where ListOfSomeObjects extends Iterable<SomeObject>)
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T04:25:30+00:00Added an answer on June 18, 2026 at 4:25 am

    Unfortunately, what you’re trying to do is very involved, because of the combination of type erasure and limitations of the reflections API.

    It’s true that you can get the generic arguments of a superclass using a combination of Class.getGenericSuperclass and ParameterizedType.getActualTypeArguments. This is the mechanism that e.g. Guava’s TypeToken class uses to capture generic type arguments. But what you’re asking for here is the generic type argument of an interface that may have been implemented at any point in the inheritance chain – notwithstanding that interfaces can themselves inherit from each other while freely resolving or declaring new type parameters.

    To demonstrate, take the following method:

    static void inspect(Object o) {
        Type type = o.getClass();
        while (type != null) {
            System.out.print(type + " implements");
            Class<?> rawType =
                    (type instanceof ParameterizedType)
                    ? (Class<?>)((ParameterizedType)type).getRawType()
                    : (Class<?>)type;
            Type[] interfaceTypes = rawType.getGenericInterfaces();
            if (interfaceTypes.length > 0) {
                System.out.println(":");
                for (Type interfaceType : interfaceTypes) {
                    if (interfaceType instanceof ParameterizedType) {
                        ParameterizedType parameterizedType = (ParameterizedType)interfaceType;
                        System.out.print("  " + parameterizedType.getRawType() + " with type args: ");
                        Type[] actualTypeArgs = parameterizedType.getActualTypeArguments();
                        System.out.println(Arrays.toString(actualTypeArgs));
                    }
                    else {
                        System.out.println("  " + interfaceType);
                    }
                }
            }
            else {
                System.out.println(" nothing");
            }
            type = rawType.getGenericSuperclass();
        }
    }
    

    This will reflect on an object and climb its inheritance chain to report on its implemented interfaces and their generic arguments (if applicable).

    Let’s try it on the first case you listed:

    inspect(new ArrayList<SomeObject>());
    

    This prints:

    class java.util.ArrayList implements:
      interface java.util.List with type args: [E]
      interface java.util.RandomAccess
      interface java.lang.Cloneable
      interface java.io.Serializable
    java.util.AbstractList<E> implements:
      interface java.util.List with type args: [E]
    java.util.AbstractCollection<E> implements:
      interface java.util.Collection with type args: [E]
    class java.lang.Object implements nothing
    

    You can see that the type parameter E has not been resolved. This is perfectly understandable given type erasure – at runtime the bytecode instructions corresponding to new ArrayList<SomeObject>() have no concept of SomeObject.

    The case of the anonymous class is different:

    inspect(new Iterable<SomeObject>() {
        @Override
        public Iterator<SomeObject> iterator() {
            throw new UnsupportedOperationException();
        }
    });
    

    Prints:

    class sandbox.Main$1 implements:
      interface java.lang.Iterable with type args: [class sandbox.SomeObject]
    class java.lang.Object implements nothing
    

    Here, we have the type argument available at runtime since the anonymous class resolved the type parameter by implementing Iterable<SomeObject>. ListOfSomeObjects and any of its subclasses would work for the same reason.

    Okay, so as long as some class in the inheritance chain resolves the type parameter E along the way, we can match against it? Unfortunately no, at least not with the method above:

    inspect(new ArrayList<SomeObject>() { });
    

    This prints:

    class sandbox.Main$1 implements nothing
    java.util.ArrayList<sandbox.SomeObject> implements:
      interface java.util.List with type args: [E]
      interface java.util.RandomAccess
      interface java.lang.Cloneable
      interface java.io.Serializable
    java.util.AbstractList<E> implements:
      interface java.util.List with type args: [E]
    java.util.AbstractCollection<E> implements:
      interface java.util.Collection with type args: [E]
    class java.lang.Object implements nothing
    

    You can see that the type argument for ArrayList is known to be SomeObject, but that’s where it stops. There’s no connecting relationship between the type parameters. The reason is this bit of code:

    Class<?> rawType =
            (type instanceof ParameterizedType)
            ? (Class<?>)((ParameterizedType)type).getRawType()
            : (Class<?>)type;
    Type[] interfaceTypes = rawType.getGenericInterfaces();
    

    getGenericInterfaces is the only way to get type argument information for the interfaces, but that method is declared by Class, not Type. Whenever the method has a ParameterizedType instance, which holds the state representing its subclass’s generic-ness, it’s forced to call getRawType, which returns the Class singleton devoid of type argument information. It’s a catch-22 that results in only being able to get the type arguments of interfaces implemented with concrete type arguments.

    I don’t know of any reflection API method that matches type arguments with the parameters they resolve. Theoretically one could write reflective code that climbed up the inheritance chain, located the class that implemented Iterable (or a subinterface) and then climbed back down until it matched the corresponding type argument. Unfortunately I can’t think if how this would be implemented. Classes are free to declare type parameters with any name and in any order they want, so naive matching based on name or position is out. Maybe somebody else can contribute a solution.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following problem: I have create annotation for Security: @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.TYPE})
I have written a java annotation that looks like this: @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) // can
In my rails 3.1 app, I have specific files that are to be loaded
I have a specific class C and I would like to overload some math
I have a specific requirement that all children of a particular JComponent have double
I have a specific question, that could use a general answer... When building Multi-Tier
I have a PHP script that is using get_dns_record to retrieve and display specific
I have a hierarchy of classes that all derive from a base type and
I have a C# application that creates shortcuts to launch other programs with specific
I have a simple form: <form id=frm action=process.php method=post> <input type=text id=shortcut name=shortcut />

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.