Can fields of a Java class be of multiple types without using generics?
I have a class whose instances will be serialized Therefore, this class implements serializable This class has a field of type list. Of course, it must also be serializable Imagine this class looks like this:
import java.io.Serializable; import java.util.List; public class Report implements Serializable { private static final long serialVersionUID = 12345L; private List<Record> records = new ArrayList<>(); }
Now I know that ArrayList is serializable, but I'd rather declare that my field is an interface type
Our sonarqube has problems analyzing code It complains that the field record should also be some serializable type, and sonarqube is correct
But since this field is an implementation detail (private member), I don't want to use generics on the class
This is my question: can fields of some interface types be declared as multiple (Interface) types using self application constraints instead of generics?
For reference only: I know it can be projected to many types, but it's completely different
Object o = (List<Serializable> & Serializable) new ArrayList<Serializable>();
Although unnecessary, the above content is completely legal
Solution
It seems that your fields are private anyway, so it doesn't matter whether it's list or ArrayList You can set this field as a serializable ArrayList and use list in getters
public class Report implements Serializable { private ArrayList<Record> records = new ArrayList<>(); ... public List<Record> getRecords() { return this.records; } }
(although this does not answer whether a field can have multiple types of questions, it may be the solution to your actual problem.)