You can pass a class type as a parameter using the Class Class . Please note that this is a generic type. In addition, the instanceof operator only works on reference types, so you have to flip it to make it work:
public static List<View> getAllChildren(View v, Class<?> myClass) { if (myClass.isInstance(v)) { resultList.add(v); } }
To get the type of Class to be passed this way, you can simply use the name of the class you want with the addition of ".class". For example, if you want to call this method with the Button class, you would do it like this:
getAllChildren(view, Button.class);
Or, if you have an instance of something you need, you should use the getClass() method:
Button b = new Button(); getAllChildren(view, b.getClass());
As Evan LaHurd mentions in a comment, isInstance() checks if the two classes are compatible, so they may not be the same. If you want to make sure that they are exactly the same, you can check for equality:
myClass.equals(v.getClass());
or
myClass == v.getClass();
will also work in this case, as indicated by bayou.io
source share