amol anerao
amol anerao

Reputation: 257

Method return type using enclosed Generic class?

I am trying to write a generic request generator method which will return different objects like below:

GenricClass<Object1> genCls1 = getNewRequest(Object1.class);
GenricClass<Object2> genCls2 = getNewRequest(Object2.class);
GenricClass<Object3> genCls3 = getNewRequest(Object3.class);

I want this getNewRequest to return an object which has enclosing generic class object.

How should the signature of my getNewRequest method ?

public `?` getNewRequest(Class classtype) {...}

Upvotes: 4

Views: 120

Answers (3)

fairtrax
fairtrax

Reputation: 426

something like that:

public <T> GenericClass<T> getNewRequest(Class<T> classtype) {

}

Upvotes: 0

Eran
Eran

Reputation: 393781

You can either declare a generic type parameter in the class that contains the method getNewRequest, or directly in the method.

For example, declare generic parameter T in the method getNewRequest:

public <T> GenricClass<T> getNewRequest(Class<T> classtype)

Upvotes: 4

Naman
Naman

Reputation: 31868

Using the classType instance of T as an argument and returning a GenericClass of the same class type. Somewhat like :

public GenericClass<T> getNewRequest(T classtype) { 
}

Upvotes: 0

Related Questions