You wrote:
I want to use it (or something similar) so that my method accepts several arguments, each of which is a member of this other class.
I do not think that this can be done as a safe type without any ugly hacks, for example, including an instance of a class along with an object.
The problem is that with VarArgs you are actually being passed in an array. But you cannot have an array with different types of objects in it, they should all be the same (or subclasses, so if you have X [] y, then each element must be a subclass of X)
If your function can really deal with several types, you can create something like a class that stores an instance of the class along with an instance of T and passes in the var args list of variables of this container.
So for example, you could
class TypedInstance<T>{ Class<T> type; T instance; }
and then a function that looks something like
public whatever(TypedInstance<? extends Object>... whatever){ ... doSomethingWith(whatever[0].type, whatever[0].instance); ... }
These types of hacks are necessary due to erasure of the Java type. The general parameter is deleted at run time, so if you want to use it, you need to return it.
Chad okere
source share