How do I tell the compiler that every Observablelist<O> I pass as an argument will contain a certain method?

Asked

Viewed 63 times

2

I have the following research method:

public class Pesquisa {
private static <O> ObservableList<O> pesquisarPorNome(ObservableList<O> listaObservavel, String pesquisa) {
    ObservableList<O> novaLista = FXCollections.observableArrayList();
    for(int x = 0; x<listaObservavel.size(); x++) {
        if(listaObservavel.get(x).getNome().toLowerCase().contains(pesquisa.toLowerCase()));
        novaLista.add(listaObservavel.get(x));
    }
    return novaLista;
}

I don’t want to write this method in all classes, so I created this method separate from all classes containing the method getNome() will use. I generalized everything and beauty, but error precisely in the method getNome() saying that he does not recognize this method.

How can I tell the compiler that all ObservableList that I will pass as argument will contain this method?

Remembering that I will pass ObservableLists of several different classes, but they will always contain a getNome().

1 answer

4


You must restrict what you can use as a parameter:

private static <O extends AlgumTipo>

I put in the Github for future reference.

where AlgumTipo can be a class, interface or other type that in your contract has the method getNome(), so the compiler will only accept a type that inherits this type and as he knows that the object has this method he lets pass.

Obviously it does not compile if it attempts to pass an object of a type other than the one specified or derived from it. It is not enough to have the method, it has to be a type derived from the writing in extends, or himself if possible.

So I think you need to create this general type. There is no generalization without a common ascendant.

This is called bounded type Parameter, that is, it is a type parameter restricted to what will work in this context.

If I can’t do this guy and everything I want to do with this method pesquisarPorNome() can have this characteristic so there is no solution.

I gave the most specific answer I could within what was posted in the question.

  • Hello, thanks for the response, I made a Searchable interface, everything worked fine at first, but at the time I called the method searchName(Observablelist<Searchable> listObservavel, String search) passing as argument Search.search(mainApp.getGruposData(), searchTextField.gettext()) not a Group, being that Group implements Searchable,?

  • It’s too confusing to answer and it’s another question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.