Can a Java class field have several types without using generics?

I have a class whose instances will be serialized. Thus, the class implements Serializable. The class has a type field List, which should also be Serializable. Imagine a class looks something 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 what it ArrayListis Serializable, but I would prefer my field to have some type of interface.

The problem occurs when our SonarQube parses the code. He complains that the field recordsmust be of some type Serializable, and SonarQube is right.

But because the field is an implementation detail (private member), I don't want to use generics for the class.

: , - generics, () ?

FYI: , , - .

Object o = (List<Serializable> & Serializable) new ArrayList<Serializable>();

, .

+4
2

: , .

, , - - . Java Java 6, Java 8 . , . .

0

, private , List ArrayList. ArrayList List getter.

public class Report implements Serializable {

    private ArrayList<Record> records = new ArrayList<>();

    ...

    public List<Record> getRecords() {
        return this.records;
    }
}

( , , .)

0

Source: https://habr.com/ru/post/1654132/


All Articles