Common with variable type arguments

I want to do something like

public interface Foo<R, P...> { public R bar(P...) {/*misc*/} } 

to get an array of types to use in my related implementation. Is this possible in java?

Varargs is designed so that I have the number of arguments for this class.

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. These classes are defined when a common character is associated.

I know there is work around, but is there a safe type for this?

+7
source share
2 answers

Since you apparently want the bar accept several parameters of different types (for what it is used ), I would suggest making one parameter instead. You can then make this single parameter a container that contains each of the individual β€œparameters” that you want to use.

In general, it would be better to make a class for each set of parameters that you want to use with this method so that you have good names for each of the objects it contains. However, you can also do something like create a series of tuple types (like Pair ) for use as holders.

Here is an example:

 public class Foo<R, P> { /* * Not sure how you intend to provide any kind of implementation * here since you don't know what R or P are. */ public R bar(P parameters) { ... } } public class SomeFoo extends Foo<SomeResult, Pair<Baz, Bar>> { public SomeResult bar(Pair<Baz, Bar> parameters) { ... } } SomeFoo foo = ... SomeResult result = foo.bar(Pair.of(baz, bar)); 
+7
source

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.

+2
source

All Articles