How to return class type of a generic class with generic?

Iarwa1N

Suppose I have an interface like this;

public interface Validator<T> {
    Class<T> type();
}

If I want to implement this interface with an object, there is not any problem;

public OrderValidator implements Validator<Order>{ 
   Class<Order> type(){ 
      return Order.class; 
   }
}

But I can't implement this interface if I pass a Collection as generic type like this;

public CollectionValidator implements Validator<Collection<Item>>{

    Class<Collection<Item>> type(){
        //how can I implement this method to return type of Collection<Item> ?
    }
}

How can I implement type() method to return type of Collection< Item> ?

Collection< Item>.class does not work.

halfbit

If you just want to make it compile then try:

public interface Validator<T> {
    Class<T> type();
}
public static class CollectionValidator<Item> implements Validator<Collection<Item>>{
    @SuppressWarnings("unchecked") 
    public Class<Collection<Item>> type() {
        return (Class<Collection<Item>>) (Class<?>) Collection.class;
    }
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to return the Class of a generic type

Return a Class instance with its generic type

How to determine the class of a generic type?

How to force type on return value in a generic class?

How to force type on return value in a generic class?

How to get Class for generic type?

Getting class of return generic type possible?

Method return type using enclosed Generic class?

How to use a helper generic of type class of type

Delegate for generic class and method with generic return type

Using type variable as a return type in a generic class

How to work with generic type array and generic type class as parameter in constructor?

How can I return a class instance with a generic type as an interface with a generic type?

How does getClass().getName() return class name of the generic type?

How to explicitly define the return type of a generic returned class in TypeScript?

How to return instance of concrete class from method with generic return type

Generic type parameters C# - How to generic class return type

How to define a generic type that is not a class?

Checking type of generic class

Class with Generic Type

Typescript: Wrap function return type of generic class

Stream return class type generic

Return class of generic type in default interface method

How to return generic class with opaque type

how to reference the Type in the Concrete class of a generic class

mypy: How to declare the return type of a method returning self in a generic class?

Infer Typescript class to return the generic type based of generic value

Infer generic class type

How to wrap a class that has generic type methods with a class that has a generic type and no generic type arguments on the methods?