Reputation: 3939
Is there a way to supply a object of Class
as an argument to a generic method?
For example, I have a method:
public <T> Queue <T> getSomething (...)
And I have an object of Class
, such as
Class<?> key = ...
Is there a way I can supply the key
as the generic argument for the getSomething(...)
method? A pseudo-coded example would be:
Queue<key> queue = object.<key>getSomething(...)
Upvotes: 0
Views: 570
Reputation: 122449
You can't do this, because it would be useless.
Generics type parameters is purely a compile-time type-checking facility. Therefore, what would be the point of a type parameter that is not known at compile time? You would not be able to say anything about it, and you would not be able to do anything with it.
Upvotes: 2
Reputation: 86411
You can pass a class object into a method declared like this:
public <T> Queue<T> getSomething( Class<T> type, ... ) { ... }
Upvotes: 0
Reputation: 533530
You can pass it as an argument, like any other argument
Class<T> tClass = ...
Queue<T> queue = object.getSomething(tClass, ...);
Upvotes: 0