I have a variable that must meet two conditions, and I want to set them in the definition
I know that I can define either condition with an individual variable, like
While Java does not directly support intersection types like A&B, such types do appear in type parameter bounds and capture conversions. We can express A&B with a layer of abstraction.
public class ValueAB
{
public final T v;
// constructor ...
}
public class ClassAB
{
public final Class clazz;
// constructor ...
}
Instead of A&B, Class extends A&B>, we use wrappers ValueAB, ClassAB
ClassAB> clazz = new ClassAB<>(Foo.class);
ValueAB> value = new ValueAB<>(clazz.c.newInstance());
value.v.methodOfA();
value.v.methodOfB();
This solution would require a wrapper for each combination of As and Bs.
Another solution is to use only A as type parameter bound; B will be supplied by wildcard bound. This is probably better if you need to express multiple A&B1, A&B2, ... types at use site.
public class ValueA
{
public final T v;
...
}
public class ClassA
{
public final Class c;
...
}
---
ClassA extends B> clazz = new ClassA<>(Foo.class);
ValueA extends B> value = new ValueA<>(clazz.c.newInstance());
If it's confusing how wildcard works in these cases, see my article on wildcard
A 3rd solution is free of A or B at declaration site of wrappers; the use site provides A and B.
public class Value
{
public final T v;
...
}
public class Clazz
{
public final Class c;
...
}
---
Clazz extends A, B> clazz = new Clazz<>(Foo.class);
Value extends A, B> value = new Value<>(clazz.c.newInstance());
This is however probably too confusing.