Class as function argument

I have a function that filters a list of some values ​​and uses the instanseof construct:

public static List<View> getAllChildren(View v) { /* ... */ if (v instanceof Button) { resultList.add(v); } /* ... */ } 

I want to make it more general and set it as a Button function parameter:

  public static List<View> getAllChildren(View v, ? myClass) { /* ... */ if (v instanceof myClass) { resultList.add(v); } /* ... */ } 

But I do not know how to pass myClass to a function. Please tell me how can I generalize this function?

+6
source share
2 answers

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

+8
source

If you need more flexibility, you can make your getAllChildren method acceptable for any filter using Java 8 lambdas:

 import java.util.function.*; class Test { public static void main(String... args) { check(new Integer(1), o -> o instanceof Integer); // Prints "That it". check(new Boolean(true), o -> o instanceof Integer); // Prints "That not it". } static void check(Object o, Predicate<Object> check) { if (check.test(o)) System.out.println("That it"); else System.out.println("That not it"); } } 

Or use the strategy template if you want, or if Java 8 is not available.

For your purpose, the gla3dr solution is most likely the best, but if you need BIG POWER, consider these options.

+3
source

All Articles