Is it possible to narrow the type of a field in a Java class without making the containing class itself generic?
The generic example would be something like this:
abstract class MyClass {
//...
}
interface MyInterface {
//...
}
class MyConcreteClass<T extends MyClass & MyInterface> {
private T value;
}
Is there any way to do the following:
class MyConcreteClass {
private MyClass & MyInterface value;
}
This is essentially equivalent to MyConcreteClass or the raw MyConcreteClass type. In my implementation the type parameter will vary over the lifetime of the object (cursed mutability! It is imposed upon me by JPA!) and so the type annotation seems somewhat superfluous.
- EDIT -
There is an additional restriction I forgot to mention. We will also have this:
class SubA extends MyClass
class SubB extends MyClass
class SubC extends MyClass
class SubSubA extends SubA implements MyInterface
class SubSubB extends SubB implements MyInterface
class SubSubC extends SubC implements MyInterface
Thus, simply declaring an abstract subclass of MyClass that implements MyInterface is not a suitable solution.
Also, the ultimate field type must be a concrete type, rather than simply an interface representing the intersection, for the simple reason that JPA-persisted entites cannot be referenced by their interface types. That is, a persistent field in a JPA entity class must be of either a primitive type or a concrete entity type.