Turn many subclass specific methods into one

Hello

I have 4 different methods to get different objects that derive from a superclass, I want to be able to call a method passing a class as a parameter and getting an ArrayList

This are the 4 methods:

ArrayList<CampoTexto> camposTexto() {
  ArrayList<CampoTexto> camposTexto = new ArrayList<CampoTexto>();
  for (ObjUI objUI : objsUI) if (objUI instanceof CampoTexto) camposTexto.add((CampoTexto)objUI);
  return camposTexto;
}

ArrayList<Boton> botones() {
  ArrayList<Boton> botones = new ArrayList<Boton>();
  for (ObjUI objUI : objsUI) if (objUI instanceof Boton) botones.add((Boton)objUI);
  return botones;
}

ArrayList<CajaTexto> cajasTexto() {
  ArrayList<CajaTexto> cajasTexto = new ArrayList<CajaTexto>();
  for (ObjUI objUI : objsUI) if (objUI instanceof CajaTexto) cajasTexto.add((CajaTexto)objUI);
  return cajasTexto;
}
  
ArrayList<BarraDes> barrasDes() {
  ArrayList<BarraDes> barrasDes = new ArrayList<BarraDes>();
  for (ObjUI objUI : objsUI) if (objUI instanceof CajaTexto) barrasDes.add((BarraDes)objUI);
  return barrasDes;
}

And I’m trying to make something like this:

ArrayList<ObjUI> objsUI(Class clase) {
  ArrayList<ObjUI> objsUI = new ArrayList<ObjUI>();
  for (ObjUI objUI : objsUI) if (clase.isInstance(objUI)) objsUI.add(objUI);
  return objsUI;
}

The problem is that when I try to use the method like this:
for (CajaTexto cajaTexto : objsUI(CajaTexto.class)) cajaTexto.escribir(tecla);
it can’t cast from ObjUI to CajaTexto even thought ObjUI is te superclass of CajaTexto, not even like this:
for (CajaTexto cajaTexto : (ArrayList<CajaTexto>)objsUI(CajaTexto.class)) cajaTexto.escribir(tecla);

I’ve read about bounded type parameters and some runtime wathever class but i can’t get that to work either

Thank you
Have a nice day

1 Like
// https://Discourse.Processing.org/t/
// turn-many-subclass-specific-methods-into-one/18463/2

// GoToLoop (2020-Mar-06)

import java.util.Collection;
import java.util.List;

final List<ObjUI> objsUI = new ArrayList<ObjUI>();

void setup() {
  objsUI.add(new ObjUI());
  objsUI.add(new CampoTexto());
  objsUI.add(new Boton());
  objsUI.add(new CajaTexto());
  objsUI.add(new BarraDes());

  println(objsUI);

  final List<CajaTexto> cajas = filterBySubType(objsUI, CajaTexto.class);
  println(cajas);

  for (final Boton boton : filterBySubType(objsUI, Boton.class)) println(boton);

  exit();
}

static final <T> List<T>
  filterBySubType(final Collection<? super T> source, final Class<T> type) {

  final List<T> output = new ArrayList<T>();
  if (type == null || source == null || source.isEmpty()) return output;
  for (final Object o : source) if (type.isInstance(o)) output.add((T) o);
  return output;
}

class ObjUI {
  @Override String toString() {
    return getClass().getSimpleName();
  }
}

class CampoTexto extends ObjUI {
}

class Boton extends ObjUI {
}

class CajaTexto extends ObjUI {
}

class BarraDes extends ObjUI {
}
1 Like